package com.uzai.console.service.takebal.impl;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.User;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.entity.WxpubUser;
import com.uzai.common.entity.WxworkUser;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.msg.NoticeMsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.Math;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateFormatUtil;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.DesensitizeUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.CacheKey;
import com.uzai.console.constant.Const;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.dto.alipaymchbatch.AlipayBatchPayDto;
import com.uzai.console.dto.feign.userextinfo.UserExtInfoQueryDto;
import com.uzai.console.dto.feign.usertakebal.UserTakeBalQueryResultDto;
import com.uzai.console.dto.feign.usertakebal.UserTakeBalTransAccountDto;
import com.uzai.console.dto.feign.uzaimanage.SysRunlogWarningDto;
import com.uzai.console.dto.takebal.usertakebal.*;
import com.uzai.console.entity.*;
import com.uzai.console.entity.es.EsUserExtInfo;
import com.uzai.console.enums.AlipayMchBatchDetailStatusEnum;
import com.uzai.console.enums.AlipayMchBatchStatusEnum;
import com.uzai.console.mapper.*;
import com.uzai.console.service.CommonService;
import com.uzai.console.service.alipaymch.AlipayMchBatchPayService;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.HistoryDataFeignService;
import com.uzai.console.service.feign.UserExtInfoFeignService;
import com.uzai.console.service.feign.UserTakeBalFeignService;
import com.uzai.console.service.feign.UzaiManageFeignService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.takebal.UserTakeBalService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.vo.alipaymchbatch.AlipayMchBatchTransVo;
import com.uzai.console.vo.takebal.usertakebal.UserTakeBalPageVo;
import com.uzai.console.vo.takebal.usertakebal.UserTakeBalReportVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StopWatch;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/***
 * @author liuqi
 * @date 2021年08月25日 20:18
 */
@Service
public class UserTakeBalServiceImpl extends CommonService implements UserTakeBalService {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserTakeBalMapper userTakeBalMapper;
    @Autowired
    private WechatUserMapper wechatUserMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private UserAccDetailMapper userAccDetailMapper;
    @Autowired
    private UserTakeBalFeignService userTakeBalFeignService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private UserTypeMapper userTypeMapper;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private SysPluginMapper sysPluginMapper;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private UserExtInfoFeignService userExtInfoFeignService;
    @Autowired
    private WxworkUserMapper wxworkUserMapper;
    @Autowired
    private WxpubUserMapper wxpubUserMapper;
    @Autowired
    private AppUserMapper appUserMapper;
    @Autowired
    private AlipayMchBatchPayService alipayMchBatchPayService;
    @Autowired
    private AlipayMchAuthMapper alipayMchAuthMapper;
    @Autowired
    private AlipayMchBatchMapper alipayMchBatchMapper;
    @Autowired
    private AlipayMchBatchDetailMapper alipayMchBatchDetailMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxqGroupManagePlanMapper wxqGroupManagePlanMapper;
    @Autowired
    private WxqWorkGroupManagePlanMapper wxqWorkGroupManagePlanMapper;
    @Autowired
    private HistoryDataFeignService historyDataFeignService;
    @Autowired
    private UzaiManageFeignService uzaiManageFeignService;

    @Autowired
    private RiskLevelMapper riskLevelMapper;

    /**
     * 分页查询账号提现列表
     *
     * @param userTakeBalQuery
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public Page<UserTakeBalPageVo> findUserTakeBalList(UserTakeBalQuery userTakeBalQuery) {

        //根据机器人列表查询需要增加限制时间
        if (userTakeBalQuery.getDeviceUniqueIdList() != null && userTakeBalQuery.getDeviceUniqueIdList().size() > 0) {
            if (userTakeBalQuery.getDeviceUniqueIdList().size() >= 100) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "机器人列表查询条件数量不能超过100个");
            }

            String val = (String) redisTemplate.opsForValue().get(String.format(CacheKey.TAKEBAL_QUERY_PARA_DEVICELIST, userTakeBalQuery.getMerId()));
            if (StringUtils.isNotBlank(val)) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "选择机器人列表条件查询1分钟只允许一次查询请求");
            }
            //往reids插入本次下载，允许1分钟下载一次，避免频繁提交
            redisTemplate.opsForValue().set(String.format(CacheKey.TAKEBAL_QUERY_PARA_DEVICELIST, userTakeBalQuery.getMerId()), userTakeBalQuery.getMerId() + "", 1, TimeUnit.MINUTES);
        }

        //判断是否需要脱敏
        Boolean tuominFlag = true;
        String cmstype_requestusers_wxid_verified = (String) redisTemplate.opsForValue().get(String.format(Const.SmsType.CMSTYPE_TAKEBAL_ALIPAY, userTakeBalQuery.getMerId()));
        if (StringUtils.isNotBlank(cmstype_requestusers_wxid_verified)) {
            tuominFlag = false;
        }

        //查询会员id是否能查询到数据，如果能查询到数据，则先查询该会员id的信息
        Long userId = userTakeBalQuery.getUserId();
        User user = null; //会员信息
        int validOrderCount = 0; //该会员订单总量
        int takeBalCount = 0;   //提现次数

        if (userId != null) {
            //提现总数
            UserTakeBalQuery userTakeBalQueryUser = new UserTakeBalQuery();
            userTakeBalQueryUser.setMerId(userTakeBalQuery.getMerId());
            userTakeBalQueryUser.setUserId(userId);
            UserTakeBalReportVo userTakeBalReportVo = userTakeBalMapper.selectUserTakeBalReport(userTakeBalQueryUser);
            if (userTakeBalReportVo != null) {
                takeBalCount = Tools.getInteger(userTakeBalReportVo.getTakeBalCount());
            }

            //通过会员ID查询会员类型信息
            user = userService.findUserInfo(userId, null, userTakeBalQuery.getMerId());
            //查询有效订单笔数
            if (user != null && StringUtils.isNotBlank(user.getDeviceType())) {
                UserExtInfoQueryDto userExtInfoQueryDto = new UserExtInfoQueryDto();
                userExtInfoQueryDto.setMerId(user.getMerId());
                DeviceTypeEnum deviceTypeEnum = DeviceTypeEnum.getByKey(user.getDeviceType());
                if (deviceTypeEnum != null) {
                    userExtInfoQueryDto.setDeviceType(deviceTypeEnum.getId());
                }
                userExtInfoQueryDto.setBizUserId(user.getBizUserId());
                List<String> keys = new ArrayList<>();
                keys.add("ValidOrderCount"); //首字母大写
                userExtInfoQueryDto.setKeys(keys);

                //查询用户额外信息
                StopWatch stopWatch = new StopWatch();
                stopWatch.start();

                UzaiRespVo<EsUserExtInfo> uzaiRespVo = userExtInfoFeignService.getUserextinfo(userExtInfoQueryDto);
                logger.info("----提现列表查询会员订单总量----uzaiRespVo=" + JSONObject.toJSONString(uzaiRespVo));

                stopWatch.stop();
                logger.info("-提现列表查询会员订单总量：" + stopWatch.prettyPrint());
                //超过10秒的事务，报警
                if (stopWatch.getTotalTimeSeconds() > 10) {
                    SysRunlogWarningDto sysRunlogWarningDto = new SysRunlogWarningDto();
                    sysRunlogWarningDto.setText("提现列表查询会员订单总量，超过10秒的请求监控！\n类名：UserTakeBalServiceImpl" + "\n方法：findUserTakeBalList" + "\n接口：getUserextinfo" + "\n耗时：" + stopWatch.getTotalTimeSeconds());
                    UzaiRespVo<Object> objectUzaiRespVo = uzaiManageFeignService.sysRunlogWarning(sysRunlogWarningDto);
                    logger.info("--调用官方钉钉报警超过10秒未处理完成的提现列表查询会员订单总量接口---para={},result={}", JSONObject.toJSONString(sysRunlogWarningDto), JSONObject.toJSONString(objectUzaiRespVo));
                }


                if (uzaiRespVo != null && uzaiRespVo.getCode() == 200) {
                    EsUserExtInfo esUserExtInfo = uzaiRespVo.getData();
                    if (esUserExtInfo != null) {
                        validOrderCount = esUserExtInfo.getValidOrderCount();
                    }
                }
            }
        }

        //新建返回到页面的LIST对象
        List<UserTakeBalPageVo> userTakeBalPageVoList = new ArrayList<>();

        //执行分页查询对象
        Page<UserTakeBal> page = new Page<>();
        userTakeBalQuery.convert(page);

        List<UserTakeBal> userTakeBalList = null;
        //if (super.checkStartEndTimeIsHistoryQuery(userTakeBalQuery.getQueryStartTime(), userTakeBalQuery.getQueryEndTime(), null)) {
        if(StringUtils.isNotBlank(userTakeBalQuery.getTableSuffix())){
            //String tableSuffix = DateTime.of(userTakeBalQuery.getQueryEndTime() * 1000L).toString("yyMM");
            UzaiRespVo<Page<UserTakeBal>> listUzaiRespVoRes = historyDataFeignService.pageTakeBalHistory(userTakeBalQuery.getTableSuffix(), userTakeBalQuery);
            if (listUzaiRespVoRes.getCode() != 200) {
                throw new BusinessException("提现列表查询失败");
            }
            if (listUzaiRespVoRes.getData() != null) {
                userTakeBalList = listUzaiRespVoRes.getData().getRecords();
                page.setTotal(listUzaiRespVoRes.getData().getTotal());
            }

        }
        // 反之查询90天内的订单数据
        else {
            userTakeBalList = userTakeBalMapper.findByList(page, userTakeBalQuery);
        }

        if (null != userTakeBalList) {
            for (UserTakeBal userTakeBal : userTakeBalList) {
                UserTakeBalPageVo userTakeBalPageVo = new UserTakeBalPageVo();
                BeanUtils.copyProperties(userTakeBal, userTakeBalPageVo);

                //提现总金额(提现金额+奖励金额)
                Double takeTotalMoney = Math.add(Tools.getDouble(userTakeBal.getTakeBal()), Tools.getDouble(userTakeBal.getTakeRewardBal()));
                userTakeBalPageVo.setTakeTotalMoney(takeTotalMoney);

                //提现方式
                TakeBalTypeEnum takeBalType = TakeBalTypeEnum.getById(userTakeBalPageVo.getType());
                if (takeBalType != null) {
                    userTakeBalPageVo.setTypeName(takeBalType.getDesc());
                }
                //提现状态
                TakeBalStatusEnum takeBalStatus = TakeBalStatusEnum.getById(userTakeBalPageVo.getStatus());
                if (takeBalStatus != null) {
                    userTakeBalPageVo.setStatusName(takeBalStatus.getDesc());
                }
                //支付方式
                TransTypeEnum transType = TransTypeEnum.getById(userTakeBalPageVo.getTransType());
                if (transType != null) {
                    userTakeBalPageVo.setTransTypeName(transType.getDesc());
                }

                //查询机器人信息
                Device device = deviceService.findDeviceInfoByDeviceUniqueId(userTakeBalPageVo.getDeviceUniqueId(), userTakeBalPageVo.getDeviceType(), userTakeBalQuery.getMerId());
                if (device != null) {
                    userTakeBalPageVo.setDeviceId(device.getDeviceId());
                    userTakeBalPageVo.setDeviceName(device.getDeviceName());
                    userTakeBalPageVo.setDeviceRemark(device.getDeviceRemark());
                }

                if (user != null) {
                    userTakeBalPageVo.setIdentity(user.getIdentity());
                    userTakeBalPageVo.setIdentityName(IdentityEnum.getById(user.getIdentity()).getDesc());
                    userTakeBalPageVo.setBalance(Tools.getDouble(user.getBalance()));
                    userTakeBalPageVo.setIntegral(Tools.getInteger(user.getIntegral()));
                }

                //赋值订单总量
                userTakeBalPageVo.setOrderCount(validOrderCount);

                //赋值提现总次数
                userTakeBalPageVo.setTakeBalCount(takeBalCount);
                //自动查询下一条提现开关
                Object object = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.USER_TAKE_BLA_FIND_NEXT_FLAG.getKey(), userTakeBalQuery.getMerId()));
                if (object != null) {
                    userTakeBalPageVo.setNextFlag(Integer.parseInt(object.toString()));
                }

                //是否脱敏处理
                if (tuominFlag) {
                    userTakeBalPageVo.setAlipayName(DesensitizeUtil.left(Tools.getStr(userTakeBalPageVo.getAlipayName()), 1));
                    userTakeBalPageVo.setAlipayAccount(DesensitizeUtil.around(Tools.getStr(userTakeBalPageVo.getAlipayAccount()), 3, 2));
                }

                // 查询风险值
                WechatUser wechatUser = wechatUserMapper.selectById(userId, userTakeBal.getMerId());
                if (wechatUser != null && wechatUser.getRegSource() != null) {
                    //RiskLevel riskLevel = riskLevelMapper.selectByScore(wechatUser.getRiskScore());
                    //userTakeBalPageVo.setRiskLevelName(riskLevel.getName());
                    //userTakeBalPageVo.setRiskScore(wechatUser.getRiskScore());
                }

                userTakeBalPageVoList.add(userTakeBalPageVo);
            }
        }

        //返回到页面分页对象
        Page<UserTakeBalPageVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(userTakeBalPageVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询用户提现详情
     *
     * @param userTakeBalIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public UserTakeBalPageVo findUserTakeBalInfo(UserTakeBalIdDto userTakeBalIdDto) {
        UserTakeBalPageVo userTakeBalPageVo = new UserTakeBalPageVo();
        if (userTakeBalIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        UserTakeBal userTakeBal = userTakeBalMapper.selectById(userTakeBalIdDto.getId(), userTakeBalIdDto.getMerId());

        if (userTakeBal == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该数据不存在或是3个月之前的历史数据");
        }

        BeanUtils.copyProperties(userTakeBal, userTakeBalPageVo);

        //提现总金额(提现金额+奖励金额)
        Double takeTotalMoney = Math.add(Tools.getDouble(userTakeBal.getTakeBal()), Tools.getDouble(userTakeBal.getTakeRewardBal()));
        userTakeBalPageVo.setTakeTotalMoney(takeTotalMoney);

        //提现方式
        TakeBalTypeEnum takeBalType = TakeBalTypeEnum.getById(userTakeBal.getType());
        if (takeBalType != null) {
            userTakeBalPageVo.setTypeName(takeBalType.getDesc());
        }
        //提现状态
        TakeBalStatusEnum takeBalStatus = TakeBalStatusEnum.getById(userTakeBal.getStatus());
        if (takeBalStatus != null) {
            userTakeBalPageVo.setStatusName(takeBalStatus.getDesc());
        }
        //支付方式
        TransTypeEnum transType = TransTypeEnum.getById(userTakeBal.getTransType());
        if (transType != null) {
            userTakeBalPageVo.setTransTypeName(transType.getDesc());
        }

        //机器人信息
        Device device = deviceService.findDeviceInfoByDeviceUniqueId(userTakeBal.getDeviceUniqueId(), userTakeBal.getDeviceType(), userTakeBal.getMerId());
        if (device != null) {
            userTakeBalPageVo.setDeviceId(device.getDeviceId());
            userTakeBalPageVo.setDeviceName(device.getDeviceName());
            userTakeBalPageVo.setDeviceRemark(device.getDeviceRemark());
        }

        //提现总数
        UserTakeBalQuery userTakeBalQueryUser = new UserTakeBalQuery();
        userTakeBalQueryUser.setMerId(userTakeBal.getMerId());
        userTakeBalQueryUser.setUserId(userTakeBal.getUserId());
        UserTakeBalReportVo userTakeBalReportVo = userTakeBalMapper.selectUserTakeBalReport(userTakeBalQueryUser);
        if (userTakeBalReportVo != null) {
            userTakeBalPageVo.setTakeBalCount(Tools.getInteger(userTakeBalReportVo.getTakeBalCount()));
        }

        //通过会员ID查询会员类型信息
        User user = userService.findUserInfo(userTakeBal.getUserId(), userTakeBal.getDeviceType(), userTakeBalIdDto.getMerId());
        if (user != null) {
            userTakeBalPageVo.setIdentity(user.getIdentity());
            userTakeBalPageVo.setIdentityName(IdentityEnum.getById(user.getIdentity()).getDesc());
            userTakeBalPageVo.setBalance(Tools.getDouble(user.getBalance()));
            userTakeBalPageVo.setIntegral(Tools.getInteger(user.getIntegral()));
            userTakeBalPageVo.setUserRegTime(user.getRegTime());
            userTakeBalPageVo.setUserType(user.getUserType());
            if (user.getUserType() != null) {
                UserType userType = userTypeMapper.selectById(user.getUserType(), user.getMerId());
                if (userType != null) {
                    userTakeBalPageVo.setUserTypeName(userType.getName());
                }
            }

            //查询有效订单笔数
            if (StringUtils.isNotBlank(userTakeBalPageVo.getDeviceType())) {
                UserExtInfoQueryDto userExtInfoQueryDto = new UserExtInfoQueryDto();
                userExtInfoQueryDto.setMerId(userTakeBal.getMerId());
                DeviceTypeEnum deviceTypeEnum = DeviceTypeEnum.getByKey(userTakeBalPageVo.getDeviceType());
                if (deviceTypeEnum != null) {
                    userExtInfoQueryDto.setDeviceType(deviceTypeEnum.getId());
                }
                userExtInfoQueryDto.setBizUserId(user.getBizUserId());
                List<String> keys = new ArrayList<>();
                keys.add("ValidOrderCount"); //首字母大写
                userExtInfoQueryDto.setKeys(keys);

                //查询用户额外信息
                StopWatch stopWatch = new StopWatch();
                stopWatch.start();

                UzaiRespVo<EsUserExtInfo> uzaiRespVo = userExtInfoFeignService.getUserextinfo(userExtInfoQueryDto);

                stopWatch.stop();
                //logger.info("-获取提现总金额接口分析：" + stopWatch.prettyPrint());
                //超过10秒的事务，报警
                if (stopWatch.getTotalTimeSeconds() > 10) {
                    SysRunlogWarningDto sysRunlogWarningDto = new SysRunlogWarningDto();
                    sysRunlogWarningDto.setText("提现列表查询会员订单总量，超过10秒的请求监控！\n类名：UserTakeBalServiceImpl" + "\n方法：findUserTakeBalInfo" + "\n接口：getUserextinfo" + "\n耗时：" + stopWatch.getTotalTimeSeconds());
                    UzaiRespVo<Object> objectUzaiRespVo = uzaiManageFeignService.sysRunlogWarning(sysRunlogWarningDto);
                    logger.info("--调用官方钉钉报警超过10秒未处理完成的提现列表查询会员订单总量接口---para={},result={}", JSONObject.toJSONString(sysRunlogWarningDto), JSONObject.toJSONString(objectUzaiRespVo));
                }

                logger.info("----提现列表查询会员订单总量----uzaiRespVo=" + JSONObject.toJSONString(uzaiRespVo));
                if (uzaiRespVo != null && uzaiRespVo.getCode() == 200) {
                    EsUserExtInfo esUserExtInfo = uzaiRespVo.getData();
                    if (esUserExtInfo != null) {
                        userTakeBalPageVo.setOrderCount(esUserExtInfo.getValidOrderCount());
                    }
                }
            }
        }

        //30天成功提现统计
        UserTakeBalQuery userTakeBalQueryUser_byDays = new UserTakeBalQuery();
        userTakeBalQueryUser_byDays.setMerId(userTakeBal.getMerId());
        userTakeBalQueryUser_byDays.setUserId(userTakeBal.getUserId());
        int now = DateUtil.getNowTime();
        Integer queryEndTime = now;
        //30天之前的时间
        Integer queryStartTime = queryEndTime - 30 * 24 * 3600;
        userTakeBalQueryUser_byDays.setQueryStartTime(queryStartTime);
        userTakeBalQueryUser_byDays.setQueryEndTime(queryEndTime);
        //自动提现成功和手动审核成功
        userTakeBalQueryUser_byDays.setStatusList(Arrays.asList(TakeBalStatusEnum.TBS_AUTO_TAKEBAL_SUCCESS.getValue(), TakeBalStatusEnum.TBS_MANUAL_AUDIT_SUCCESS.getValue()));
        UserTakeBalReportVo userTakeBalReportVo_byDays = userTakeBalMapper.selectUserTakeBalReport(userTakeBalQueryUser_byDays);
        if (userTakeBalReportVo_byDays != null) {
            userTakeBalPageVo.setUserTakeBalCountByDays(Tools.getInteger(userTakeBalReportVo_byDays.getTakeBalCount()));
            //提现总金额=总提现金额+奖励金额
            Double userTakeBalAmountByDays = Math.add(Tools.getDouble(userTakeBalReportVo_byDays.getTakeBalTotal()), Tools.getDouble(userTakeBalReportVo_byDays.getTakeRewardBalTotal()));
            userTakeBalPageVo.setUserTakeBalAmountByDays(userTakeBalAmountByDays);
        }

        //自动查询下一条提现开关
        Object object = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.USER_TAKE_BLA_FIND_NEXT_FLAG.getKey(), userTakeBalIdDto.getMerId()));
        if (object != null) {
            userTakeBalPageVo.setNextFlag(Integer.parseInt(object.toString()));
        }

        //是否脱敏处理
        //判断是否需要脱敏
        Boolean tuominFlag = true;
        String cmstype_requestusers_wxid_verified = (String) redisTemplate.opsForValue().get(String.format(Const.SmsType.CMSTYPE_TAKEBAL_ALIPAY, userTakeBalIdDto.getMerId()));
        if (StringUtils.isNotBlank(cmstype_requestusers_wxid_verified)) {
            tuominFlag = false;
        }
        if (tuominFlag) {
            userTakeBalPageVo.setAlipayName(DesensitizeUtil.left(Tools.getStr(userTakeBalPageVo.getAlipayName()), 1));
            userTakeBalPageVo.setAlipayAccount(DesensitizeUtil.around(Tools.getStr(userTakeBalPageVo.getAlipayAccount()), 3, 2));
        }

        return userTakeBalPageVo;
    }

    /**
     * 设置自动查询下一条开关
     *
     * @param userTakeBalNexSetDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void setNextFlag(UserTakeBalNexSetDto userTakeBalNexSetDto) {
        //更新redis
        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.USER_TAKE_BLA_FIND_NEXT_FLAG.getKey(), userTakeBalNexSetDto.getMerId()), userTakeBalNexSetDto.getNextFlag());
    }

    /**
     * 查询下一条用户提现详情
     *
     * @param userTakeBalQuery
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public UserTakeBalPageVo findNextUserTakeBalInfo(UserTakeBalQuery userTakeBalQuery) {
        //请输入当前的id
        if (userTakeBalQuery.getIdEnd() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入当前的ID");
        }
        //清空tradeno条件
        userTakeBalQuery.setTradeno(null);

        //默认只查询第一页
        userTakeBalQuery.setCurrent(1);
        //默认只查询一条
        userTakeBalQuery.setSize(1);
        //排序
        List<OrderItem> orderItemList = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        orderItem.setColumn("id");
        orderItem.setAsc(false);
        orderItemList.add(orderItem);
        userTakeBalQuery.setOrderItemList(orderItemList);
        //默认分页查询
        Page<UserTakeBalPageVo> pageVoPage = findUserTakeBalList(userTakeBalQuery);
        if (pageVoPage != null && pageVoPage.getRecords() != null && pageVoPage.getRecords().size() > 0) {
            UserTakeBalIdDto userTakeBalIdDto = new UserTakeBalIdDto();
            userTakeBalIdDto.setId(pageVoPage.getRecords().get(0).getId());
            userTakeBalIdDto.setMerId(userTakeBalQuery.getMerId());
            return findUserTakeBalInfo(userTakeBalIdDto);
        }
        return null;
    }


    /**
     * 提现审核
     *
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void checkUserTakeBal(UserTakeBalIdDto userTakeBalIdDto) {
        if (userTakeBalIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        UserTakeBal userTakeBal = userTakeBalMapper.selectById(userTakeBalIdDto.getId(), userTakeBalIdDto.getMerId());

        if (userTakeBal == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该数据不存在或是3个月之前的历史数据");
        }

        if (userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_PENDING.getValue().intValue() && userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue().intValue()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现记录状态不是待处理或者自动提现失败");
        }

        User user = userService.findUserInfo(userTakeBal.getUserId(), userTakeBal.getDeviceType(), userTakeBalIdDto.getMerId());
        if (user == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现记录绑定的会员不存在");
        }

        //查询机器人
        Device device = deviceService.findDeviceInfoByDeviceUniqueId(userTakeBal.getDeviceUniqueId(), userTakeBal.getDeviceType(), userTakeBalIdDto.getMerId());
        if (device == null) {
            //如果提现记录的机器人不存在，则取会员默认客户端机器人
            device = deviceService.findDeviceInfoByDeviceUniqueId(user.getDeviceUniqueId(), user.getDeviceType(), userTakeBalIdDto.getMerId());
            if (device == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请配置会员默认客户端");
            }
        }

        //配置方案
        ConfigPlan configPlan = null;
        //接收消息业务会员id（机器人提现和群内提现）
        String bizUserId = null;
        //机器人提现
        if (StringUtils.isBlank(userTakeBal.getWxGroupId())) {
            bizUserId = user.getBizUserId();
            configPlan = configPlanMapper.selectById(device.getConfigId(), userTakeBal.getMerId());
        } else {//群内提现
            bizUserId = userTakeBal.getWxGroupId();
            if (DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(userTakeBal.getDeviceType())) {//个人微信群
                //缓存中的微信群管理方案key
                String redisKey_wxgroup_manageplan_key = String.format(RedisCacheKeyEnum.WXGROUP_MANAGEPLAN_CONFIG.getKey(), userTakeBal.getMerId(), device.getDeviceId(), userTakeBal.getWxGroupId());
                Object wxgroup_manageplan_id = redisTemplate.opsForValue().get(redisKey_wxgroup_manageplan_key);
                if (wxgroup_manageplan_id == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该群管理方案缓存");
                }
                configPlan = configPlanMapper.selectById((Long) wxgroup_manageplan_id, userTakeBal.getMerId());
            } else {
                //缓存中的企业微信群管理方案key
                String redisKey_wxworkgroup_manageplan_key = String.format(RedisCacheKeyEnum.WXGROUP_WORK_MANAGEPLAN_CONFIG.getKey(), userTakeBal.getMerId(), device.getDeviceId(), userTakeBal.getWxGroupId());
                Object wxworkgroup_manageplan_id = redisTemplate.opsForValue().get(redisKey_wxworkgroup_manageplan_key);
                if (wxworkgroup_manageplan_id == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该群管理方案缓存");
                }
                configPlan = configPlanMapper.selectById((Long) wxworkgroup_manageplan_id, userTakeBal.getMerId());
            }
        }

        if (configPlan == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现记录绑定的机器人的配置方案不存在");
        }

        //发送提现审核成功文本消息
        SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserTakeBalId(), userTakeBalIdDto.getMerId());
        if (sysPlugin == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现记录绑定的机器人的配置方案中的提现插件不存在");
        }

        int now = DateUtil.getNowTime();

        //修改提现记录状态为4-手动审核成功
        userTakeBal.setStatus(TakeBalStatusEnum.TBS_MANUAL_AUDIT_SUCCESS.getValue());
        userTakeBal.setTransType(TransTypeEnum.OFFLINE.getValue());
        userTakeBal.setUpdateTime(now);
        userTakeBal.setPayTime(now);
        int i = userTakeBalMapper.updateStatus(userTakeBal);

        if (i != 1) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
        }

        //发送提现审核成功文本消息
        JSONObject jsonObject = JSONObject.parseObject(sysPlugin.getData());
        if (jsonObject != null) {
            //申请提现成功-通过审核，不走系统支付
            String message = jsonObject.getString("manual_take_succ");
            if (StringUtils.isNotBlank(message)) {

                //已提现总金额和冻结订单返利金额-从ES的会员额外信息index中获取
                double takeBalTotalMoney = 0.00;
                double frozenOrderRewardMoney = 0.00;

                //查询用户额外信息
                UserExtInfoQueryDto userExtInfoQueryDto = new UserExtInfoQueryDto();
                userExtInfoQueryDto.setMerId(userTakeBalIdDto.getMerId());
                userExtInfoQueryDto.setDeviceType(DeviceTypeEnum.getByKey(userTakeBal.getDeviceType()).getId()); //个人用户
                userExtInfoQueryDto.setBizUserId(user.getBizUserId());
                userExtInfoQueryDto.setKeys(Arrays.asList("FrozenOrderRewardMoney", "TakeBalTotalMoney"));


                StopWatch stopWatch = new StopWatch();
                stopWatch.start();

                UzaiRespVo<EsUserExtInfo> uzaiRespVo_userExtInfo = userExtInfoFeignService.getUserextinfo(userExtInfoQueryDto);
                logger.info("----获取提现总金额----para={}, result={}", JSONObject.toJSONString(userExtInfoQueryDto), JSONObject.toJSONString(uzaiRespVo_userExtInfo));

                stopWatch.stop();
                //logger.info("-获取提现总金额接口分析：" + stopWatch.prettyPrint());
                //超过10秒的事务，报警
                if (stopWatch.getTotalTimeSeconds() > 10) {
                    SysRunlogWarningDto sysRunlogWarningDto = new SysRunlogWarningDto();
                    sysRunlogWarningDto.setText("获取提现总金额接口，超过10秒的请求监控！\n类名：UserTakeBalServiceImpl" + "\n方法：checkUserTakeBal" + "\n接口：getUserextinfo" + "\n耗时：" + stopWatch.getTotalTimeSeconds());
                    UzaiRespVo<Object> objectUzaiRespVo = uzaiManageFeignService.sysRunlogWarning(sysRunlogWarningDto);
                    logger.info("--调用官方钉钉报警超过10秒未处理完成的获取提现总金额接口---para={},result={}", JSONObject.toJSONString(sysRunlogWarningDto), JSONObject.toJSONString(objectUzaiRespVo));
                }

                if (uzaiRespVo_userExtInfo != null && uzaiRespVo_userExtInfo.getCode() == 200) {
                    EsUserExtInfo esUserExtInfo = uzaiRespVo_userExtInfo.getData();
                    if (esUserExtInfo != null) {
                        takeBalTotalMoney = esUserExtInfo.getTakeBalTotalMoney();
                        frozenOrderRewardMoney = esUserExtInfo.getFrozenOrderRewardMoney();
                    }
                }

                message = message.replace("[昵称]", user.getNickName());
                message = message.replace("[提现金额]", String.valueOf(userTakeBal.getTakeBal()));
                message = message.replace("[当前时间]", DateFormatUtil.formatDefault(new Date()));
                //message = message.replace("[已提现总金额]", String.valueOf(Math.add(takeBalTotalMoney, userTakeBal.getTakeBal()))); //由于事务还未提交，故此时需要已提现总金额+本次提现金额
                message = message.replace("[已提现总金额]", String.valueOf(takeBalTotalMoney)); //去掉了事务故,ES中查询的已提现金额为最新的，故不需要增加本次提现金额
                message = message.replace("[冻结订单返利金额]", String.valueOf(frozenOrderRewardMoney));
                message = message.replace("[奖励金额]", String.valueOf(Tools.getDouble(userTakeBal.getTakeRewardBal())));
                message = message.replace("[奖励积分]", String.valueOf(Tools.getInteger(userTakeBal.getTakeRewardInte())));
                message = message.replace("[支付宝账号]", DesensitizeUtil.around(Tools.getStr(user.getAlipayAccount()), 3, 4));
                message = message.replace("[支付宝姓名]", DesensitizeUtil.left(Tools.getStr(user.getAlipayName()), 1));
                message = message.replace("[当前余额]", String.valueOf(Tools.getDouble(user.getBalance())));
                //发送MQ消息
                MsgDto<NoticeMsgDto> msgDto = new MsgDto<>();
                NoticeMsgDto noticeMsgDto = new NoticeMsgDto();
                msgDto.setContent(noticeMsgDto);
                msgDto.setId(IdWorker.getId());
                msgDto.setDeviceType(device.getRecvmsgType());
                msgDto.setDeviceUniqueId(userTakeBal.getDeviceUniqueId());
                msgDto.setMerId(userTakeBal.getMerId());
                msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
                noticeMsgDto.setContent(message);
                noticeMsgDto.setBizUserId(bizUserId);
                noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
                noticeMsgDto.setGroupId(null);
                noticeMsgDto.setNickName(user.getNickName());
                noticeMsgDto.setMsgSource(1);
                noticeMsgDto.setDelay(0);
                noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
                noticeMsgPushProducerService.sendMessage(msgDto);
            }
        }


    }

    /**
     * 拒绝并返还
     *
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Transactional
    public void refuseAndReturnUserTakeBal(UserTakeBalIdDto userTakeBalIdDto) {

        if (userTakeBalIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        UserTakeBal userTakeBal = userTakeBalMapper.selectById(userTakeBalIdDto.getId(), userTakeBalIdDto.getMerId());

        if (userTakeBal == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该数据不存在或是3个月之前的历史数据");
        }

        if (userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_PENDING.getValue().intValue() && userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue().intValue()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现记录状态不是待处理或者自动提现失败");
        }

        User user = userService.findUserInfo(userTakeBal.getUserId(), userTakeBal.getDeviceType(), userTakeBalIdDto.getMerId());
        if (user == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现记录绑定的会员不存在");
        }

        //查询机器人
        Device device = deviceService.findDeviceInfoByDeviceUniqueId(userTakeBal.getDeviceUniqueId(), userTakeBal.getDeviceType(), userTakeBalIdDto.getMerId());
        if (device == null) {
            //如果提现记录的机器人不存在，则取会员默认客户端机器人
            device = deviceService.findDeviceInfoByDeviceUniqueId(user.getDeviceUniqueId(), user.getDeviceType(), userTakeBalIdDto.getMerId());
            if (device == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请配置默认客户端");
            }
        }

        //配置方案
        ConfigPlan configPlan = null;
        //接收消息业务会员id（机器人提现和群内提现）
        String bizUserId = null;
        //机器人提现
        if (StringUtils.isBlank(userTakeBal.getWxGroupId())) {
            configPlan = configPlanMapper.selectById(device.getConfigId(), userTakeBal.getMerId());
            bizUserId = user.getBizUserId();
        } else {//群内提现
            bizUserId = userTakeBal.getWxGroupId();
            if (DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(userTakeBal.getDeviceType())) {//个人微信群
                //缓存中的微信群管理方案key
                String redisKey_wxgroup_manageplan_key = String.format(RedisCacheKeyEnum.WXGROUP_MANAGEPLAN_CONFIG.getKey(), userTakeBal.getMerId(), device.getDeviceId(), userTakeBal.getWxGroupId());
                Object wxgroup_manageplan_id = redisTemplate.opsForValue().get(redisKey_wxgroup_manageplan_key);
                if (wxgroup_manageplan_id == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该群管理方案缓存");
                }
                configPlan = configPlanMapper.selectById((Long) wxgroup_manageplan_id, userTakeBal.getMerId());
            } else {
                //缓存中的企业微信群管理方案key
                String redisKey_wxworkgroup_manageplan_key = String.format(RedisCacheKeyEnum.WXGROUP_WORK_MANAGEPLAN_CONFIG.getKey(), userTakeBal.getMerId(), device.getDeviceId(), userTakeBal.getWxGroupId());
                Object wxworkgroup_manageplan_id = redisTemplate.opsForValue().get(redisKey_wxworkgroup_manageplan_key);
                if (wxworkgroup_manageplan_id == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该群管理方案缓存");
                }
                configPlan = configPlanMapper.selectById((Long) wxworkgroup_manageplan_id, userTakeBal.getMerId());
            }
        }
        if (configPlan == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现记录的配置方案不存在");
        }

        //发送提现审核成功文本消息
        SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserTakeBalId(), userTakeBalIdDto.getMerId());
        if (sysPlugin == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现记录配置方案中的提现插件不存在");
        }


        Integer now = DateUtil.getNowTime();

        //修改提现记录状态为5-拒绝并返还
        userTakeBal.setStatus(TakeBalStatusEnum.TBS_REFUSE_AND_RETURN.getValue());
        if (StringUtils.isNotBlank(userTakeBalIdDto.getFailMsg())) {
            userTakeBal.setFailMsg(userTakeBalIdDto.getFailMsg());
        }
        userTakeBal.setUpdateTime(now);
        int i = userTakeBalMapper.updateStatus(userTakeBal);
        if (i != 1) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
        }

        //新余额
        double newBalance = 0.00d;
        //新积分
        int newIntegral = 0;

        //修改用户余额
        if (userTakeBal.getDeviceType().equals(DeviceTypeEnum.DT_PC_WECHAT.getKey())) { //个人微信用户

            WechatUser wechatUser = wechatUserMapper.selectById(userTakeBal.getUserId(), userTakeBalIdDto.getMerId());
            if (wechatUser == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该个人微信用户不存在");
            }

            //计算用户余额并修改
            Double oldBalance = wechatUser.getBalance();
            //修改余额
            newBalance = Math.add(oldBalance, userTakeBal.getTakeBal());
            newIntegral = wechatUser.getIntegral();
            wechatUser.setBalance(newBalance);
            wechatUser.setUpdateTime(now);
            int j = wechatUserMapper.updateBalance(wechatUser);
            if (j != 1) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
            }

        } else if (userTakeBal.getDeviceType().equals(DeviceTypeEnum.DT_WORK_WECHAT.getKey())) {//企业微信用户
            WxworkUser wxworkUser = wxworkUserMapper.selectById(userTakeBal.getUserId(), userTakeBalIdDto.getMerId());
            if (wxworkUser == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信用户不存在");
            }

            //计算用户余额并修改
            Double oldBalance = wxworkUser.getBalance();
            //修改余额
            newBalance = Math.add(oldBalance, userTakeBal.getTakeBal());
            newIntegral = wxworkUser.getIntegral();
            wxworkUser.setBalance(newBalance);
            wxworkUser.setUpdateTime(now);
            int j = wxworkUserMapper.updateBalance(wxworkUser);
            if (j != 1) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
            }
        } else if (userTakeBal.getDeviceType().equals(DeviceTypeEnum.WX_PUB.getKey())) {//公众号用户
            WxpubUser wxpubUser = wxpubUserMapper.selectById(userTakeBal.getUserId(), userTakeBalIdDto.getMerId());
            if (wxpubUser == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该公众号用户不存在");
            }

            //计算用户余额并修改
            Double oldBalance = wxpubUser.getBalance();
            //修改余额
            newBalance = Math.add(oldBalance, userTakeBal.getTakeBal());
            newIntegral = wxpubUser.getIntegral();
            wxpubUser.setBalance(newBalance);
            wxpubUser.setUpdateTime(now);
            int j = wxpubUserMapper.updateBalance(wxpubUser);
            if (j != 1) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
            }
        } else if (userTakeBal.getDeviceType().equals(DeviceTypeEnum.APP.getKey())) {//APP用户
            AppUser appUser = appUserMapper.selectById(userTakeBal.getUserId(), userTakeBalIdDto.getMerId());
            if (appUser == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该APP用户不存在");
            }

            //计算用户余额并修改
            Double oldBalance = appUser.getBalance();
            //修改余额
            newBalance = Math.add(oldBalance, userTakeBal.getTakeBal());
            newIntegral = appUser.getIntegral();
            appUser.setBalance(newBalance);
            appUser.setUpdateTime(now);

            int j = appUserMapper.updateBalance(appUser);
            if (j != 1) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
            }
        } else {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "目前还未支持该类型用户");
        }

        //增加账号入账明细
        UserAccDetail wechatUserAccDetail = new UserAccDetail();
        wechatUserAccDetail.setId(IdWorker.getId());
        wechatUserAccDetail.setMerId(userTakeBalIdDto.getMerId());
        wechatUserAccDetail.setUserId(userTakeBal.getUserId());
        wechatUserAccDetail.setDeviceUniqueId(userTakeBal.getDeviceUniqueId());
        wechatUserAccDetail.setDeviceType(userTakeBal.getDeviceType());
        wechatUserAccDetail.setChangeInte(0);
        wechatUserAccDetail.setChangeBal(userTakeBal.getTakeBal());
        wechatUserAccDetail.setNewBal(newBalance);
        wechatUserAccDetail.setNewInte(newIntegral);
        wechatUserAccDetail.setType(AccDetailTypeEnum.TAKE_BALANCE_REBACK.getValue());
        wechatUserAccDetail.setTradeno(userTakeBal.getTradeno());
        wechatUserAccDetail.setRemark(null);
        wechatUserAccDetail.setCreateTime(now);
        wechatUserAccDetail.setUpdateTime(now);
        int insert = userAccDetailMapper.insert(wechatUserAccDetail);
        if (insert != 1) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "增加账号明细失败");
        }

        //发送提现拒绝并返还文本消息
        JSONObject jsonObject = JSONObject.parseObject(sysPlugin.getData());
        if (jsonObject != null) {
            //提现拒绝并返还用户账户-手动
            String message = jsonObject.getString("take_refuse_add_bal");
            if (StringUtils.isNotBlank(message)) {

                message = message.replace("[昵称]", user.getNickName());
                message = message.replace("[提现金额]", String.valueOf(userTakeBal.getTakeBal()));
                message = message.replace("[当前时间]", DateFormatUtil.formatDefault(new Date()));

                //发送MQ消息
                MsgDto<NoticeMsgDto> msgDto = new MsgDto<>();
                NoticeMsgDto noticeMsgDto = new NoticeMsgDto();
                msgDto.setContent(noticeMsgDto);
                msgDto.setId(IdWorker.getId());
                msgDto.setDeviceType(device.getRecvmsgType());
                msgDto.setDeviceUniqueId(userTakeBal.getDeviceUniqueId());
                msgDto.setMerId(userTakeBal.getMerId());
                msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
                noticeMsgDto.setContent(message);
                noticeMsgDto.setBizUserId(bizUserId);
                noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
                noticeMsgDto.setGroupId(null);
                noticeMsgDto.setNickName(user.getNickName());
                noticeMsgDto.setMsgSource(1);
                noticeMsgDto.setDelay(0);
                noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
                noticeMsgPushProducerService.sendMessage(msgDto);
            }
        }
    }

    /**
     * 拒绝并扣除
     *
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void refuseAndDecUserTakeBal(UserTakeBalIdDto userTakeBalIdDto) {

        if (userTakeBalIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        UserTakeBal userTakeBal = userTakeBalMapper.selectById(userTakeBalIdDto.getId(), userTakeBalIdDto.getMerId());

        if (userTakeBal == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该数据不存在或是3个月之前的历史数据");
        }

        if (userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_PENDING.getValue().intValue() && userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue().intValue()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现记录状态不是待处理或者自动提现失败");
        }

        User user = userService.findUserInfo(userTakeBal.getUserId(), userTakeBal.getDeviceType(), userTakeBalIdDto.getMerId());
        if (user == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现记录绑定的会员不存在");
        }

        //查询机器人
        Device device = deviceService.findDeviceInfoByDeviceUniqueId(userTakeBal.getDeviceUniqueId(), userTakeBal.getDeviceType(), userTakeBalIdDto.getMerId());
        if (device == null) {
            //如果提现记录的机器人不存在，则取会员默认客户端机器人
            device = deviceService.findDeviceInfoByDeviceUniqueId(user.getDeviceUniqueId(), user.getDeviceType(), userTakeBalIdDto.getMerId());
            if (device == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请配置默认客户端");
            }
        }

        //配置方案
        ConfigPlan configPlan = null;
        //接收消息业务会员id（机器人提现和群内提现）
        String bizUserId = null;
        //机器人提现
        if (StringUtils.isBlank(userTakeBal.getWxGroupId())) {
            bizUserId = user.getBizUserId();
            configPlan = configPlanMapper.selectById(device.getConfigId(), userTakeBal.getMerId());
        } else {//群内提现

            bizUserId = userTakeBal.getWxGroupId();

            if (DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(userTakeBal.getDeviceType())) {//个人微信群
                //缓存中的微信群管理方案key
                String redisKey_wxgroup_manageplan_key = String.format(RedisCacheKeyEnum.WXGROUP_MANAGEPLAN_CONFIG.getKey(), userTakeBal.getMerId(), device.getDeviceId(), userTakeBal.getWxGroupId());
                Object wxgroup_manageplan_id = redisTemplate.opsForValue().get(redisKey_wxgroup_manageplan_key);
                if (wxgroup_manageplan_id == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该群管理方案缓存");
                }
                configPlan = configPlanMapper.selectById((Long) wxgroup_manageplan_id, userTakeBal.getMerId());
            } else {
                //缓存中的企业微信群管理方案key
                String redisKey_wxworkgroup_manageplan_key = String.format(RedisCacheKeyEnum.WXGROUP_WORK_MANAGEPLAN_CONFIG.getKey(), userTakeBal.getMerId(), device.getDeviceId(), userTakeBal.getWxGroupId());
                Object wxworkgroup_manageplan_id = redisTemplate.opsForValue().get(redisKey_wxworkgroup_manageplan_key);
                if (wxworkgroup_manageplan_id == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该群管理方案缓存");
                }
                configPlan = configPlanMapper.selectById((Long) wxworkgroup_manageplan_id, userTakeBal.getMerId());
            }
        }
        if (configPlan == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现记录的配置方案不存在");
        }

        //发送提现审核成功文本消息
        SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserTakeBalId(), userTakeBalIdDto.getMerId());
        if (sysPlugin == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现记录的配置方案中的提现插件不存在");
        }

        Integer now = DateUtil.getNowTime();

        //修改提现记录状态为6-拒绝并扣除
        userTakeBal.setStatus(TakeBalStatusEnum.TBS_REFUSE_AND_DEC.getValue());
        userTakeBal.setUpdateTime(DateUtil.getNowTime());
        int i = userTakeBalMapper.updateStatus(userTakeBal);
        if (i != 1) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
        }

        //发送提现拒绝并扣除文本消息
        JSONObject jsonObject = JSONObject.parseObject(sysPlugin.getData());
        if (jsonObject != null) {
            //提现拒绝并扣除提现金额-手动
            String message = jsonObject.getString("take_refuse_sub_bal");
            if (StringUtils.isNotBlank(message)) {

                message = message.replace("[昵称]", user.getNickName());
                message = message.replace("[提现金额]", String.valueOf(userTakeBal.getTakeBal()));
                message = message.replace("[当前时间]", DateFormatUtil.formatDefault(new Date()));

                //发送MQ消息
                MsgDto<NoticeMsgDto> msgDto = new MsgDto<>();
                NoticeMsgDto noticeMsgDto = new NoticeMsgDto();
                msgDto.setContent(noticeMsgDto);
                msgDto.setId(IdWorker.getId());
                msgDto.setDeviceType(device.getRecvmsgType());
                msgDto.setDeviceUniqueId(userTakeBal.getDeviceUniqueId());
                msgDto.setMerId(userTakeBal.getMerId());
                msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
                noticeMsgDto.setContent(message);
                noticeMsgDto.setBizUserId(bizUserId);
                noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
                noticeMsgDto.setGroupId(null);
                noticeMsgDto.setNickName(user.getNickName());
                noticeMsgDto.setMsgSource(1);
                noticeMsgDto.setDelay(0);
                noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
                noticeMsgPushProducerService.sendMessage(msgDto);
            }
        }

    }

    /**
     * 发送提现卡片
     *
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void sendcard(UserTakeBalSendCardDto userTakeBalSendCardDto) {
        if (userTakeBalSendCardDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        UserTakeBal userTakeBal = userTakeBalMapper.selectById(userTakeBalSendCardDto.getId(), userTakeBalSendCardDto.getMerId());

        if (userTakeBal == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该数据不存在或是3个月之前的历史数据");
        }

        if (userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_PENDING.getValue().intValue() && userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue().intValue()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该提现不是待处理状态或者自动提现失败");
        }

        User user = userService.findUserInfo(userTakeBal.getUserId(), userTakeBal.getDeviceType(), userTakeBalSendCardDto.getMerId());
        if (user == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现记录绑定的会员不存在");
        }

        //是否开启会员余额负数不提现验证
        if (Tools.getInteger(userTakeBalSendCardDto.getUserBalFlag()).intValue() == 1) { //开启，则需要判断会员余额是否为负数
            if (Tools.getDouble(user.getBalance()).doubleValue() < 0) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员余额为负数不处理");
            }
        }

        //查询机器人
        Device device = deviceService.findDeviceInfoByDeviceUniqueId(userTakeBal.getDeviceUniqueId(), userTakeBal.getDeviceType(), userTakeBalSendCardDto.getMerId());
        if (device == null) {
            //如果提现记录的机器人不存在，则取会员默认客户端机器人
            device = deviceService.findDeviceInfoByDeviceUniqueId(user.getDeviceUniqueId(), user.getDeviceType(), user.getMerId());
            if (device == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请配置默认客户端");
            }
        }

        //配置方案
        ConfigPlan configPlan = null;
        //接收消息业务会员id（机器人提现和群内提现）
        String bizUserId = null;
        //机器人提现
        if (StringUtils.isBlank(userTakeBal.getWxGroupId())) {
            bizUserId = user.getBizUserId();
            configPlan = configPlanMapper.selectById(device.getConfigId(), userTakeBal.getMerId());
        } else {//群内提现

            bizUserId = userTakeBal.getWxGroupId();

            if (DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(userTakeBal.getDeviceType())) {//个人微信群
                //缓存中的微信群管理方案key
                String redisKey_wxgroup_manageplan_key = String.format(RedisCacheKeyEnum.WXGROUP_MANAGEPLAN_CONFIG.getKey(), userTakeBal.getMerId(), device.getDeviceId(), userTakeBal.getWxGroupId());
                Object wxgroup_manageplan_id = redisTemplate.opsForValue().get(redisKey_wxgroup_manageplan_key);
                if (wxgroup_manageplan_id == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该群管理方案缓存");
                }
                configPlan = configPlanMapper.selectById((Long) wxgroup_manageplan_id, userTakeBal.getMerId());
            } else {
                //缓存中的企业微信群管理方案key
                String redisKey_wxworkgroup_manageplan_key = String.format(RedisCacheKeyEnum.WXGROUP_WORK_MANAGEPLAN_CONFIG.getKey(), userTakeBal.getMerId(), device.getDeviceId(), userTakeBal.getWxGroupId());
                Object wxworkgroup_manageplan_id = redisTemplate.opsForValue().get(redisKey_wxworkgroup_manageplan_key);
                if (wxworkgroup_manageplan_id == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该群管理方案缓存");
                }
                configPlan = configPlanMapper.selectById((Long) wxworkgroup_manageplan_id, userTakeBal.getMerId());
            }
        }
        if (configPlan == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现记录的配置方案不存在");
        }

        //发送提现审核成功文本消息
        SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserTakeBalId(), userTakeBalSendCardDto.getMerId());
        if (sysPlugin == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现记录的配置方案中的提现插件不存在");
        }

        //发送红包卡片
        UserTakeBalTransAccountDto userTakeBalTransAccountDto = new UserTakeBalTransAccountDto();
        userTakeBalTransAccountDto.setId(userTakeBal.getId());
        userTakeBalTransAccountDto.setUserId(userTakeBal.getUserId());
        UzaiRespVo<Boolean> uzaiRespVo = userTakeBalFeignService.sendcard(userTakeBalTransAccountDto);
        logger.info("--发送红包卡片--para={}, result={}", JSONObject.toJSONString(userTakeBalTransAccountDto), JSONObject.toJSONString(uzaiRespVo));
        if (uzaiRespVo.getCode() == 200 && uzaiRespVo.getData()) {
            //发送自动提现成功文本消息
            JSONObject jsonObject = JSONObject.parseObject(sysPlugin.getData());
            if (jsonObject != null) {
                //提现审核成功-自动提现成功
                String message = jsonObject.getString("manual_card_take_succ");
                if (StringUtils.isNotBlank(message)) {

                    //已提现总金额和冻结订单返利金额-从ES的会员额外信息index中获取
                    double takeBalTotalMoney = 0.00;
                    double frozenOrderRewardMoney = 0.00;

                    //查询用户额外信息
                    StopWatch stopWatch = new StopWatch();
                    stopWatch.start();

                    UserExtInfoQueryDto userExtInfoQueryDto = new UserExtInfoQueryDto();
                    userExtInfoQueryDto.setMerId(userTakeBalSendCardDto.getMerId());
                    userExtInfoQueryDto.setDeviceType(DeviceTypeEnum.getByKey(userTakeBal.getDeviceType()).getId()); //个人用户
                    userExtInfoQueryDto.setBizUserId(user.getBizUserId());
                    userExtInfoQueryDto.setKeys(Arrays.asList("FrozenOrderRewardMoney", "TakeBalTotalMoney"));
                    UzaiRespVo<EsUserExtInfo> uzaiRespVo_userExtInfo = userExtInfoFeignService.getUserextinfo(userExtInfoQueryDto);
                    logger.info("----获取提现总金额----para={}, result={}", JSONObject.toJSONString(userExtInfoQueryDto), JSONObject.toJSONString(uzaiRespVo_userExtInfo));

                    stopWatch.stop();
                    //logger.info("-获取提现总金额接口分析：" + stopWatch.prettyPrint());

                    //超过10秒的事务，报警
                    if (stopWatch.getTotalTimeSeconds() > 10) {
                        SysRunlogWarningDto sysRunlogWarningDto = new SysRunlogWarningDto();
                        sysRunlogWarningDto.setText("获取体现总金额接口，超过10秒的请求监控！\n类名：UserTakeBalServiceImpl" + "\n方法：sendcard" + "\n接口：getUserextinfo" + "\n耗时：" + stopWatch.getTotalTimeSeconds());
                        UzaiRespVo<Object> objectUzaiRespVo = uzaiManageFeignService.sysRunlogWarning(sysRunlogWarningDto);
                        logger.info("--调用官方钉钉报警超过10秒未处理完成的获取提现总金额接口---para={},result={}", JSONObject.toJSONString(sysRunlogWarningDto), JSONObject.toJSONString(objectUzaiRespVo));
                    }


                    if (uzaiRespVo_userExtInfo != null && uzaiRespVo_userExtInfo.getCode() == 200) {
                        EsUserExtInfo esUserExtInfo = uzaiRespVo_userExtInfo.getData();
                        if (esUserExtInfo != null) {
                            takeBalTotalMoney = esUserExtInfo.getTakeBalTotalMoney();
                            frozenOrderRewardMoney = esUserExtInfo.getFrozenOrderRewardMoney();
                        }
                    }

                    message = message.replace("[昵称]", user.getNickName());
                    message = message.replace("[提现金额]", String.valueOf(userTakeBal.getTakeBal()));
                    message = message.replace("[当前时间]", DateFormatUtil.formatDefault(new Date()));
                    message = message.replace("[已提现总金额]", String.valueOf(takeBalTotalMoney));
                    message = message.replace("[冻结订单返利金额]", String.valueOf(frozenOrderRewardMoney));
                    message = message.replace("[奖励金额]", String.valueOf(Tools.getDouble(userTakeBal.getTakeRewardBal())));
                    message = message.replace("[奖励积分]", String.valueOf(Tools.getInteger(userTakeBal.getTakeRewardInte())));
                    message = message.replace("[支付宝账号]", DesensitizeUtil.around(Tools.getStr(user.getAlipayAccount()), 3, 4));
                    message = message.replace("[支付宝姓名]", DesensitizeUtil.left(Tools.getStr(user.getAlipayName()), 1));

                    //发送MQ消息
                    MsgDto<NoticeMsgDto> msgDto = new MsgDto<>();
                    NoticeMsgDto noticeMsgDto = new NoticeMsgDto();
                    msgDto.setContent(noticeMsgDto);
                    msgDto.setId(IdWorker.getId());
                    msgDto.setDeviceType(device.getRecvmsgType());
                    msgDto.setDeviceUniqueId(userTakeBal.getDeviceUniqueId());
                    msgDto.setMerId(userTakeBal.getMerId());
                    msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
                    noticeMsgDto.setContent(message);
                    noticeMsgDto.setBizUserId(bizUserId);
                    noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
                    noticeMsgDto.setGroupId(null);
                    noticeMsgDto.setNickName(user.getNickName());
                    noticeMsgDto.setMsgSource(1);
                    noticeMsgDto.setDelay(0);
                    noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
                    noticeMsgPushProducerService.sendMessage(msgDto);
                }
            }

            //是否需要发送补充消息
            if (StringUtils.isNotBlank(userTakeBalSendCardDto.getMessage())) {//有消息，则发送
                String message = Tools.getStr(userTakeBalSendCardDto.getMessage());
                message = message.replace("[昵称]", user.getNickName());
                message = message.replace("[提现金额]", String.valueOf(userTakeBal.getTakeBal()));

                //发送MQ消息
                MsgDto<NoticeMsgDto> msgDto = new MsgDto<>();
                NoticeMsgDto noticeMsgDto = new NoticeMsgDto();
                msgDto.setContent(noticeMsgDto);
                msgDto.setId(IdWorker.getId());
                msgDto.setDeviceType(device.getRecvmsgType());
                msgDto.setDeviceUniqueId(userTakeBal.getDeviceUniqueId());
                msgDto.setMerId(userTakeBal.getMerId());
                msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
                noticeMsgDto.setContent(message);
                noticeMsgDto.setBizUserId(user.getBizUserId());
                noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
                noticeMsgDto.setGroupId(null);
                noticeMsgDto.setNickName(user.getNickName());
                noticeMsgDto.setMsgSource(1);
                noticeMsgDto.setDelay(0);
                noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
                noticeMsgPushProducerService.sendMessage(msgDto);
            }
        } else {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
        }
    }

    /**
     * 提现微信转账
     *
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void wxpay(UserTakeBalIdDto userTakeBalIdDto) {
        if (userTakeBalIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        UserTakeBal userTakeBal = userTakeBalMapper.selectById(userTakeBalIdDto.getId(), userTakeBalIdDto.getMerId());

        if (userTakeBal == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该数据不存在或是3个月之前的历史数据");
        }

        if (userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_PENDING.getValue().intValue() && userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue().intValue()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该提现不是待处理状态或者自动提现失败");
        }

        //查询用户
        User user = userService.findUserInfo(userTakeBal.getUserId(), userTakeBal.getDeviceType(), userTakeBalIdDto.getMerId());
        if (user == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //是否开启会员余额负数不提现验证
        if (Tools.getInteger(userTakeBalIdDto.getUserBalFlag()).intValue() == 1) { //开启，则需要判断会员余额是否为负数
            if (Tools.getDouble(user.getBalance()).doubleValue() < 0) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员余额为负数不处理");
            }
        }

        //查询机器人
        Device device = deviceService.findDeviceInfoByDeviceUniqueId(userTakeBal.getDeviceUniqueId(), userTakeBal.getDeviceType(), userTakeBalIdDto.getMerId());
        if (device == null) {
            //如果提现记录的机器人不存在，则取会员默认客户端机器人
            device = deviceService.findDeviceInfoByDeviceUniqueId(user.getDeviceUniqueId(), user.getDeviceType(), user.getMerId());
            if (device == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请配置默认客户端");
            }
        }

        //配置方案
        ConfigPlan configPlan = null;
        //接收消息业务会员id（机器人提现和群内提现）
        String bizUserId = null;
        //机器人提现
        if (StringUtils.isBlank(userTakeBal.getWxGroupId())) {
            bizUserId = user.getBizUserId();
            configPlan = configPlanMapper.selectById(device.getConfigId(), userTakeBal.getMerId());
        } else {//群内提现

            bizUserId = userTakeBal.getWxGroupId();

            if (DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(userTakeBal.getDeviceType())) {//个人微信群
                //缓存中的微信群管理方案key
                String redisKey_wxgroup_manageplan_key = String.format(RedisCacheKeyEnum.WXGROUP_MANAGEPLAN_CONFIG.getKey(), userTakeBal.getMerId(), device.getDeviceId(), userTakeBal.getWxGroupId());
                Object wxgroup_manageplan_id = redisTemplate.opsForValue().get(redisKey_wxgroup_manageplan_key);
                if (wxgroup_manageplan_id == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该群管理方案缓存");
                }
                configPlan = configPlanMapper.selectById((Long) wxgroup_manageplan_id, userTakeBal.getMerId());
            } else {
                //缓存中的企业微信群管理方案key
                String redisKey_wxworkgroup_manageplan_key = String.format(RedisCacheKeyEnum.WXGROUP_WORK_MANAGEPLAN_CONFIG.getKey(), userTakeBal.getMerId(), device.getDeviceId(), userTakeBal.getWxGroupId());
                Object wxworkgroup_manageplan_id = redisTemplate.opsForValue().get(redisKey_wxworkgroup_manageplan_key);
                if (wxworkgroup_manageplan_id == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该群管理方案缓存");
                }
                configPlan = configPlanMapper.selectById((Long) wxworkgroup_manageplan_id, userTakeBal.getMerId());
            }
        }
        if (configPlan == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现记录的配置方案不存在");
        }

        //发送提现审核成功文本消息
        SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserTakeBalId(), userTakeBalIdDto.getMerId());
        if (sysPlugin == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现记录的配置方案中的提现插件不存在");
        }

        //已提现总金额和冻结订单返利金额-从ES的会员额外信息index中获取
        double takeBalTotalMoney = 0.00;
        double frozenOrderRewardMoney = 0.00;

        //查询用户额外信息
        UserExtInfoQueryDto userExtInfoQueryDto = new UserExtInfoQueryDto();
        userExtInfoQueryDto.setMerId(userTakeBalIdDto.getMerId());
        userExtInfoQueryDto.setDeviceType(DeviceTypeEnum.getByKey(userTakeBal.getDeviceType()).getId()); //个人用户
        userExtInfoQueryDto.setBizUserId(user.getBizUserId());
        userExtInfoQueryDto.setKeys(Arrays.asList("FrozenOrderRewardMoney", "TakeBalTotalMoney"));

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        UzaiRespVo<EsUserExtInfo> uzaiRespVo_userExtInfo = userExtInfoFeignService.getUserextinfo(userExtInfoQueryDto);
        logger.info("----获取提现总金额----para={}, result={}", JSONObject.toJSONString(userExtInfoQueryDto), JSONObject.toJSONString(uzaiRespVo_userExtInfo));

        stopWatch.stop();
        logger.info("-获取提现总金额：" + stopWatch.prettyPrint());

        //超过10秒的事务，报警
        if (stopWatch.getTotalTimeSeconds() > 10) {
            SysRunlogWarningDto sysRunlogWarningDto = new SysRunlogWarningDto();
            sysRunlogWarningDto.setText("获取提现总金额，超过10秒的请求监控！\n类名：UserTakeBalServiceImpl" + "\n方法：wxpay" + "\n接口：getUserextinfo" + "\n耗时：" + stopWatch.getTotalTimeSeconds());
            UzaiRespVo<Object> objectUzaiRespVo = uzaiManageFeignService.sysRunlogWarning(sysRunlogWarningDto);
            logger.info("--调用官方钉钉报警超过10秒未处理完成的获取提现总金额接口---para={},result={}", JSONObject.toJSONString(sysRunlogWarningDto), JSONObject.toJSONString(objectUzaiRespVo));
        }

        if (uzaiRespVo_userExtInfo != null && uzaiRespVo_userExtInfo.getCode() == 200) {
            EsUserExtInfo esUserExtInfo = uzaiRespVo_userExtInfo.getData();
            if (esUserExtInfo != null) {
                takeBalTotalMoney = esUserExtInfo.getTakeBalTotalMoney();
                frozenOrderRewardMoney = esUserExtInfo.getFrozenOrderRewardMoney();
            }
        }

        //微信转账
        UserTakeBalTransAccountDto userTakeBalTransAccountDto = new UserTakeBalTransAccountDto();
        userTakeBalTransAccountDto.setId(userTakeBal.getId());
        userTakeBalTransAccountDto.setUserId(userTakeBal.getUserId());
        UzaiRespVo<Integer> uzaiRespVo = userTakeBalFeignService.wxpay(userTakeBalTransAccountDto);

        logger.info("--提现微信转账--para={}, result={}", JSONObject.toJSONString(userTakeBalTransAccountDto), JSONObject.toJSONString(uzaiRespVo));
        if (uzaiRespVo.getCode() == 200) {
            //自动提现成功或者手动审核成功
            if (Tools.getInteger(uzaiRespVo.getData()).intValue() == TakeBalStatusEnum.TBS_AUTO_TAKEBAL_SUCCESS.getValue().intValue()
                    || Tools.getInteger(uzaiRespVo.getData()).intValue() == TakeBalStatusEnum.TBS_MANUAL_AUDIT_SUCCESS.getValue().intValue()
                    || Tools.getInteger(uzaiRespVo.getData()).intValue() == TakeBalStatusEnum.TBS_PROCESSING.getValue().intValue() //商家付款到零钱返回为处理中
            ) {
                //发送提现审核成功文本消息
                JSONObject jsonObject = JSONObject.parseObject(sysPlugin.getData());
                if (jsonObject != null) {
                    //提现审核成功-手动打款并审核成功
                    String message = jsonObject.getString("take_succ_manual_trans");
                    //查询刚处理的最新的提现记录,验证是否是微信转账还是红包卡片
                    UserTakeBal userTakeBal_new = userTakeBalMapper.selectById(userTakeBalIdDto.getId(), userTakeBalIdDto.getMerId());
                    if (userTakeBal_new != null) {
                        Integer transType = Tools.getInteger(userTakeBal_new.getTransType());
                        if (transType.intValue() == TransTypeEnum.REDCARD.getValue()) { //红包卡片
                            message = jsonObject.getString("manual_card_take_succ");
                        }
                        //logger.info("-微信转账调用回复语-transType={}, message={}", userTakeBal_new.getTransType(), message);
                    }

                    if (StringUtils.isNotBlank(message)) {
                        //最新已提现总金额=查询出的已提现总金额+本次提现金额
                        takeBalTotalMoney = Math.add(takeBalTotalMoney, Tools.getDouble(userTakeBal.getTakeBal()));
                        message = message.replace("[昵称]", user.getNickName());
                        message = message.replace("[提现金额]", String.valueOf(userTakeBal.getTakeBal()));
                        message = message.replace("[当前时间]", DateFormatUtil.formatDefault(new Date()));
                        message = message.replace("[已提现总金额]", String.valueOf(takeBalTotalMoney));
                        message = message.replace("[冻结订单返利金额]", String.valueOf(frozenOrderRewardMoney));
                        message = message.replace("[奖励金额]", String.valueOf(Tools.getDouble(userTakeBal.getTakeRewardBal())));
                        message = message.replace("[奖励积分]", String.valueOf(Tools.getInteger(userTakeBal.getTakeRewardInte())));
                        message = message.replace("[支付宝账号]", DesensitizeUtil.around(Tools.getStr(user.getAlipayAccount()), 3, 4));
                        message = message.replace("[支付宝姓名]", DesensitizeUtil.left(Tools.getStr(user.getAlipayName()), 1));

                        //发送MQ消息
                        MsgDto<NoticeMsgDto> msgDto = new MsgDto<>();
                        NoticeMsgDto noticeMsgDto = new NoticeMsgDto();
                        msgDto.setContent(noticeMsgDto);
                        msgDto.setId(IdWorker.getId());
                        msgDto.setDeviceType(device.getRecvmsgType());
                        msgDto.setDeviceUniqueId(userTakeBal.getDeviceUniqueId());
                        msgDto.setMerId(userTakeBal.getMerId());
                        msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
                        noticeMsgDto.setContent(message);
                        noticeMsgDto.setBizUserId(bizUserId);
                        noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
                        noticeMsgDto.setGroupId(null);
                        noticeMsgDto.setNickName(user.getNickName());
                        noticeMsgDto.setMsgSource(1);
                        noticeMsgDto.setDelay(0);
                        noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
                        noticeMsgPushProducerService.sendMessage(msgDto);
                    }
                }
            } else if (Tools.getInteger(uzaiRespVo.getData()).intValue() == -1) {//ERR1-微信支付-V3-对应单号已超出重试期,请查单确认后决定是否换单请求,直接自动按拒绝并返回处理
                userTakeBalIdDto.setFailMsg("当前支付出现错误：ERR1-微信支付-V3-对应单号已超出重试期,请查单确认后决定是否换单请求。已经自动将提现金额返还用户！");
                refuseAndReturnUserTakeBal(userTakeBalIdDto);
            } else {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "转账失败!");
            }
        } else {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
        }
    }

    /**
     * 提现微信红包(仅手机版支持)
     *
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void wxRedpacket(UserTakeBalIdDto userTakeBalIdDto) {
        if (userTakeBalIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        UserTakeBal userTakeBal = userTakeBalMapper.selectById(userTakeBalIdDto.getId(), userTakeBalIdDto.getMerId());

        if (userTakeBal == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该数据不存在或是3个月之前的历史数据");
        }

        if (userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_PENDING.getValue().intValue() && userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue().intValue()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该提现不是待处理状态或者自动提现失败");
        }

        //发送红包总金额（提现金额+奖励金额）
        Double takeBalTotal = Math.add(Tools.getDouble(userTakeBal.getTakeBal()), Tools.getDouble(userTakeBal.getTakeRewardBal()));
        //判断微信红包总金额不能大于200
        if (takeBalTotal.doubleValue() > 200D) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "微信红包金额最大金额为200元");
        }

        //查询用户
        User user = userService.findUserInfo(userTakeBal.getUserId(), userTakeBal.getDeviceType(), userTakeBalIdDto.getMerId());
        if (user == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //是否开启会员余额负数不提现验证
        if (Tools.getInteger(userTakeBalIdDto.getUserBalFlag()).intValue() == 1) { //开启，则需要判断会员余额是否为负数
            if (Tools.getDouble(user.getBalance()).doubleValue() < 0) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员余额为负数不处理");
            }
        }

        //查询机器人
        Device device = deviceService.findDeviceInfoByDeviceUniqueId(userTakeBal.getDeviceUniqueId(), userTakeBal.getDeviceType(), userTakeBalIdDto.getMerId());
        if (device == null) {
            //如果提现记录的机器人不存在，则取会员默认客户端机器人
            device = deviceService.findDeviceInfoByDeviceUniqueId(user.getDeviceUniqueId(), user.getDeviceType(), user.getMerId());
            if (device == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请配置默认客户端");
            }
        }

        //只支持手机端发送微信红包提现
        if (device.getRecvmsgType().intValue() != DeviceTypeEnum.DT_ANDROID_WECHAT.getId().intValue()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "仅支持手机端微信红包提现");
        }

        //配置方案
        ConfigPlan configPlan = null;
        //接收消息业务会员id（机器人提现和群内提现）
        String bizUserId = null;
        //机器人提现
        if (StringUtils.isBlank(userTakeBal.getWxGroupId())) {
            bizUserId = user.getBizUserId();
            configPlan = configPlanMapper.selectById(device.getConfigId(), userTakeBal.getMerId());
        } else {//不允许微信红包群内提现
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "不支持微信红包群内提现");
        }
        if (configPlan == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现记录的配置方案不存在");
        }

        //发送提现审核成功文本消息
        SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserTakeBalId(), userTakeBalIdDto.getMerId());
        if (sysPlugin == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现记录的配置方案中的提现插件不存在");
        }

        //微信转账
        UserTakeBalTransAccountDto userTakeBalTransAccountDto = new UserTakeBalTransAccountDto();
        userTakeBalTransAccountDto.setId(userTakeBal.getId());
        userTakeBalTransAccountDto.setUserId(userTakeBal.getUserId());

        //调用微信红包提现
        UzaiRespVo<Integer> uzaiRespVo = userTakeBalFeignService.redpack(userTakeBalTransAccountDto);

        logger.info("--提现发送微信红包--para={}, result={}", JSONObject.toJSONString(userTakeBalTransAccountDto), JSONObject.toJSONString(uzaiRespVo));
        if (uzaiRespVo.getCode() == 200) {
            //处理中表示发送成功
            if (Tools.getInteger(uzaiRespVo.getData()).intValue() == TakeBalStatusEnum.TBS_PROCESSING.getValue().intValue()) {
                //发送提现审核成功文本消息
                JSONObject jsonObject = JSONObject.parseObject(sysPlugin.getData());
                if (jsonObject != null) {
                    //提现审核成功-手动打款并审核成功
                    String message = jsonObject.getString("take_succ_manual_trans");
                    if (StringUtils.isNotBlank(message)) {

                        //已提现总金额和冻结订单返利金额-从ES的会员额外信息index中获取
                        double takeBalTotalMoney = 0.00;
                        double frozenOrderRewardMoney = 0.00;

                        //查询用户额外信息
                        UserExtInfoQueryDto userExtInfoQueryDto = new UserExtInfoQueryDto();
                        userExtInfoQueryDto.setMerId(userTakeBalIdDto.getMerId());
                        userExtInfoQueryDto.setDeviceType(DeviceTypeEnum.getByKey(userTakeBal.getDeviceType()).getId()); //个人用户
                        userExtInfoQueryDto.setBizUserId(user.getBizUserId());
                        userExtInfoQueryDto.setKeys(Arrays.asList("FrozenOrderRewardMoney", "TakeBalTotalMoney"));

                        StopWatch stopWatch = new StopWatch();
                        stopWatch.start();

                        UzaiRespVo<EsUserExtInfo> uzaiRespVo_userExtInfo = userExtInfoFeignService.getUserextinfo(userExtInfoQueryDto);
                        logger.info("----获取提现总金额----para={}, result={}", JSONObject.toJSONString(userExtInfoQueryDto), JSONObject.toJSONString(uzaiRespVo_userExtInfo));

                        stopWatch.stop();
                        logger.info("-获取提现总金额：" + stopWatch.prettyPrint());

                        //超过10秒的事务，报警
                        if (stopWatch.getTotalTimeSeconds() > 10) {
                            SysRunlogWarningDto sysRunlogWarningDto = new SysRunlogWarningDto();
                            sysRunlogWarningDto.setText("获取提现总金额，超过10秒的请求监控！\n类名：UserTakeBalServiceImpl" + "\n方法：wxRedpacket" + "\n接口：getUserextinfo" + "\n耗时：" + stopWatch.getTotalTimeSeconds());
                            UzaiRespVo<Object> objectUzaiRespVo = uzaiManageFeignService.sysRunlogWarning(sysRunlogWarningDto);
                            logger.info("--调用官方钉钉报警超过10秒未处理完成的获取提现总金额接口---para={},result={}", JSONObject.toJSONString(sysRunlogWarningDto), JSONObject.toJSONString(objectUzaiRespVo));
                        }

                        if (uzaiRespVo_userExtInfo != null && uzaiRespVo_userExtInfo.getCode() == 200) {
                            EsUserExtInfo esUserExtInfo = uzaiRespVo_userExtInfo.getData();
                            if (esUserExtInfo != null) {
                                takeBalTotalMoney = esUserExtInfo.getTakeBalTotalMoney();
                                frozenOrderRewardMoney = esUserExtInfo.getFrozenOrderRewardMoney();
                            }
                        }

                        message = message.replace("[昵称]", user.getNickName());
                        message = message.replace("[提现金额]", String.valueOf(userTakeBal.getTakeBal()));
                        message = message.replace("[当前时间]", DateFormatUtil.formatDefault(new Date()));
                        message = message.replace("[已提现总金额]", String.valueOf(takeBalTotalMoney));
                        message = message.replace("[冻结订单返利金额]", String.valueOf(frozenOrderRewardMoney));
                        message = message.replace("[奖励金额]", String.valueOf(Tools.getDouble(userTakeBal.getTakeRewardBal())));
                        message = message.replace("[奖励积分]", String.valueOf(Tools.getInteger(userTakeBal.getTakeRewardInte())));
                        message = message.replace("[支付宝账号]", DesensitizeUtil.around(Tools.getStr(user.getAlipayAccount()), 3, 4));
                        message = message.replace("[支付宝姓名]", DesensitizeUtil.left(Tools.getStr(user.getAlipayName()), 1));

                        //发送MQ消息
                        MsgDto<NoticeMsgDto> msgDto = new MsgDto<>();
                        NoticeMsgDto noticeMsgDto = new NoticeMsgDto();
                        msgDto.setContent(noticeMsgDto);
                        msgDto.setId(IdWorker.getId());
                        msgDto.setDeviceType(device.getRecvmsgType());
                        msgDto.setDeviceUniqueId(userTakeBal.getDeviceUniqueId());
                        msgDto.setMerId(userTakeBal.getMerId());
                        msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
                        noticeMsgDto.setContent(message);
                        noticeMsgDto.setBizUserId(bizUserId);
                        noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
                        noticeMsgDto.setGroupId(null);
                        noticeMsgDto.setNickName(user.getNickName());
                        noticeMsgDto.setMsgSource(1);
                        noticeMsgDto.setDelay(0);
                        noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
                        noticeMsgPushProducerService.sendMessage(msgDto);
                    }
                }
            } else {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "转账失败!");
            }
        } else {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
        }


    }


    /**
     * 提现支付宝转账
     *
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void alipay(UserTakeBalIdDto userTakeBalIdDto) {
        if (userTakeBalIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        UserTakeBal userTakeBal = userTakeBalMapper.selectById(userTakeBalIdDto.getId(), userTakeBalIdDto.getMerId());

        if (userTakeBal == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该数据不存在或是3个月之前的历史数据");
        }

        if (userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_PENDING.getValue().intValue() && userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue().intValue()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该提现不是待处理状态或者自动提现失败");
        }

        //查询用户
        User user = userService.findUserInfo(userTakeBal.getUserId(), userTakeBal.getDeviceType(), userTakeBalIdDto.getMerId());
        if (user == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //是否开启会员余额负数不提现验证
        if (Tools.getInteger(userTakeBalIdDto.getUserBalFlag()).intValue() == 1) { //开启，则需要判断会员余额是否为负数
            if (Tools.getDouble(user.getBalance()).doubleValue() < 0) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员余额为负数不处理");
            }
        }

        //查询机器人
        Device device = deviceService.findDeviceInfoByDeviceUniqueId(userTakeBal.getDeviceUniqueId(), userTakeBal.getDeviceType(), userTakeBalIdDto.getMerId());
        if (device == null) {
            //如果提现记录的机器人不存在，则取会员默认客户端机器人
            device = deviceService.findDeviceInfoByDeviceUniqueId(user.getDeviceUniqueId(), user.getDeviceType(), user.getMerId());
            if (device == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请配置默认客户端");
            }
        }

        //配置方案
        ConfigPlan configPlan = null;
        //接收消息业务会员id（机器人提现和群内提现）
        String bizUserId = null;
        //机器人提现
        if (StringUtils.isBlank(userTakeBal.getWxGroupId())) {
            bizUserId = user.getBizUserId();
            configPlan = configPlanMapper.selectById(device.getConfigId(), userTakeBal.getMerId());
        } else {//群内提现

            bizUserId = userTakeBal.getWxGroupId();

            if (DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(userTakeBal.getDeviceType())) {//个人微信群
                //缓存中的微信群管理方案key
                String redisKey_wxgroup_manageplan_key = String.format(RedisCacheKeyEnum.WXGROUP_MANAGEPLAN_CONFIG.getKey(), userTakeBal.getMerId(), device.getDeviceId(), userTakeBal.getWxGroupId());
                Object wxgroup_manageplan_id = redisTemplate.opsForValue().get(redisKey_wxgroup_manageplan_key);
                if (wxgroup_manageplan_id == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该群管理方案缓存");
                }
                configPlan = configPlanMapper.selectById((Long) wxgroup_manageplan_id, userTakeBal.getMerId());
            } else {
                //缓存中的企业微信群管理方案key
                String redisKey_wxworkgroup_manageplan_key = String.format(RedisCacheKeyEnum.WXGROUP_WORK_MANAGEPLAN_CONFIG.getKey(), userTakeBal.getMerId(), device.getDeviceId(), userTakeBal.getWxGroupId());
                Object wxworkgroup_manageplan_id = redisTemplate.opsForValue().get(redisKey_wxworkgroup_manageplan_key);
                if (wxworkgroup_manageplan_id == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该群管理方案缓存");
                }
                configPlan = configPlanMapper.selectById((Long) wxworkgroup_manageplan_id, userTakeBal.getMerId());
            }
        }
        if (configPlan == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现记录的配置方案不存在");
        }

        //发送提现审核成功文本消息
        SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserTakeBalId(), userTakeBalIdDto.getMerId());
        if (sysPlugin == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现记录的配置方案中的提现插件不存在");
        }

        //支付宝转账
        UserTakeBalTransAccountDto userTakeBalTransAccountDto = new UserTakeBalTransAccountDto();
        userTakeBalTransAccountDto.setId(userTakeBal.getId());
        userTakeBalTransAccountDto.setUserId(userTakeBal.getUserId());
        UzaiRespVo<Integer> uzaiRespVo = userTakeBalFeignService.alipay(userTakeBalTransAccountDto);

        logger.info("--提现支付宝转账--para={}, result={}", JSONObject.toJSONString(userTakeBalTransAccountDto), JSONObject.toJSONString(uzaiRespVo));

        if (uzaiRespVo.getCode() == 200) {
            //自动提现成功或者手动审核成功
            if (Tools.getInteger(uzaiRespVo.getData()).intValue() == TakeBalStatusEnum.TBS_AUTO_TAKEBAL_SUCCESS.getValue().intValue()
                    || Tools.getInteger(uzaiRespVo.getData()).intValue() == TakeBalStatusEnum.TBS_MANUAL_AUDIT_SUCCESS.getValue().intValue()) {
                //发送提现审核成功文本消息
                JSONObject jsonObject = JSONObject.parseObject(sysPlugin.getData());
                if (jsonObject != null) {
                    //支付宝自动提现成功（2023-03-21 增加,支付宝手动转账也是用这个回复语)
                    String message = jsonObject.getString("manual_alipay_take_succ");
                    if (StringUtils.isNotBlank(message)) {

                        //已提现总金额和冻结订单返利金额-从ES的会员额外信息index中获取
                        double takeBalTotalMoney = 0.00;
                        double frozenOrderRewardMoney = 0.00;

                        //查询用户额外信息
                        UserExtInfoQueryDto userExtInfoQueryDto = new UserExtInfoQueryDto();
                        userExtInfoQueryDto.setMerId(userTakeBalIdDto.getMerId());
                        userExtInfoQueryDto.setDeviceType(DeviceTypeEnum.getByKey(userTakeBal.getDeviceType()).getId()); //个人用户
                        userExtInfoQueryDto.setBizUserId(user.getBizUserId());
                        userExtInfoQueryDto.setKeys(Arrays.asList("FrozenOrderRewardMoney", "TakeBalTotalMoney"));

                        StopWatch stopWatch = new StopWatch();
                        stopWatch.start();

                        UzaiRespVo<EsUserExtInfo> uzaiRespVo_userExtInfo = userExtInfoFeignService.getUserextinfo(userExtInfoQueryDto);
                        logger.info("----获取提现总金额----para={}, result={}", JSONObject.toJSONString(userExtInfoQueryDto), JSONObject.toJSONString(uzaiRespVo_userExtInfo));

                        stopWatch.stop();
                        logger.info("-获取提现总金额：" + stopWatch.prettyPrint());

                        //超过10秒的事务，报警
                        if (stopWatch.getTotalTimeSeconds() > 10) {
                            SysRunlogWarningDto sysRunlogWarningDto = new SysRunlogWarningDto();
                            sysRunlogWarningDto.setText("获取提现总金额，超过10秒的请求监控！\n类名：UserTakeBalServiceImpl" + "\n方法：alipay" + "\n接口：getUserextinfo" + "\n耗时：" + stopWatch.getTotalTimeSeconds());
                            UzaiRespVo<Object> objectUzaiRespVo = uzaiManageFeignService.sysRunlogWarning(sysRunlogWarningDto);
                            logger.info("--调用官方钉钉报警超过10秒未处理完成的获取提现总金额接口---para={},result={}", JSONObject.toJSONString(sysRunlogWarningDto), JSONObject.toJSONString(objectUzaiRespVo));
                        }


                        if (uzaiRespVo_userExtInfo != null && uzaiRespVo_userExtInfo.getCode() == 200) {
                            EsUserExtInfo esUserExtInfo = uzaiRespVo_userExtInfo.getData();
                            if (esUserExtInfo != null) {
                                takeBalTotalMoney = esUserExtInfo.getTakeBalTotalMoney();
                                frozenOrderRewardMoney = esUserExtInfo.getFrozenOrderRewardMoney();
                            }
                        }

                        message = message.replace("[昵称]", user.getNickName());
                        message = message.replace("[提现金额]", String.valueOf(userTakeBal.getTakeBal()));
                        message = message.replace("[当前时间]", DateFormatUtil.formatDefault(new Date()));
                        message = message.replace("[已提现总金额]", String.valueOf(takeBalTotalMoney));
                        message = message.replace("[冻结订单返利金额]", String.valueOf(frozenOrderRewardMoney));
                        message = message.replace("[奖励金额]", String.valueOf(Tools.getDouble(userTakeBal.getTakeRewardBal())));
                        message = message.replace("[奖励积分]", String.valueOf(Tools.getInteger(userTakeBal.getTakeRewardInte())));
                        message = message.replace("[支付宝账号]", DesensitizeUtil.around(Tools.getStr(user.getAlipayAccount()), 3, 4));
                        message = message.replace("[支付宝姓名]", DesensitizeUtil.left(Tools.getStr(user.getAlipayName()), 1));

                        //发送MQ消息
                        MsgDto<NoticeMsgDto> msgDto = new MsgDto<>();
                        NoticeMsgDto noticeMsgDto = new NoticeMsgDto();
                        msgDto.setContent(noticeMsgDto);
                        msgDto.setId(IdWorker.getId());
                        msgDto.setDeviceType(device.getRecvmsgType());
                        msgDto.setDeviceUniqueId(userTakeBal.getDeviceUniqueId());
                        msgDto.setMerId(userTakeBal.getMerId());
                        msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
                        noticeMsgDto.setContent(message);
                        noticeMsgDto.setBizUserId(bizUserId);
                        noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
                        noticeMsgDto.setGroupId(null);
                        noticeMsgDto.setNickName(user.getNickName());
                        noticeMsgDto.setMsgSource(1);
                        noticeMsgDto.setDelay(0);
                        noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
                        noticeMsgPushProducerService.sendMessage(msgDto);
                    }
                }
            } else {//转账失败，发送失败回复语
                //发送提现审核成功文本消息
                JSONObject jsonObject = JSONObject.parseObject(sysPlugin.getData());
                if (jsonObject != null) {
                    //支付宝手动转账失败,去数据库查询下该提现失败的错误信息（2024-01-27 增加,支付宝手动转账失败也是用这个回复语)
                    UserTakeBal userTakeBal_new = userTakeBalMapper.selectById(userTakeBal.getId(), userTakeBal.getMerId());
                    String failMsg = userTakeBal_new.getFailMsg();
                    String message = jsonObject.getString("manual_alipay_err");
                    if (StringUtils.isNotBlank(failMsg) && failMsg.contains("支付宝接口异常")) {//支付宝API接口异常
                        message = jsonObject.getString("manual_alipay_api_err");
                    }

                    if (StringUtils.isNotBlank(message)) {
                        message = message.replace("[昵称]", user.getNickName());
                        message = message.replace("[支付宝账号]", DesensitizeUtil.around(Tools.getStr(user.getAlipayAccount()), 3, 4));
                        message = message.replace("[支付宝姓名]", DesensitizeUtil.left(Tools.getStr(user.getAlipayName()), 1));
                        message = message.replace("[错误原因]", Tools.getStr(failMsg));
                        //发送MQ消息
                        MsgDto<NoticeMsgDto> msgDto = new MsgDto<>();
                        NoticeMsgDto noticeMsgDto = new NoticeMsgDto();
                        msgDto.setContent(noticeMsgDto);
                        msgDto.setId(IdWorker.getId());
                        msgDto.setDeviceType(device.getRecvmsgType());
                        msgDto.setDeviceUniqueId(userTakeBal.getDeviceUniqueId());
                        msgDto.setMerId(userTakeBal.getMerId());
                        msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
                        noticeMsgDto.setContent(message);
                        noticeMsgDto.setBizUserId(bizUserId);
                        noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
                        noticeMsgDto.setGroupId(null);
                        noticeMsgDto.setNickName(user.getNickName());
                        noticeMsgDto.setMsgSource(1);
                        noticeMsgDto.setDelay(0);
                        noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
                        noticeMsgPushProducerService.sendMessage(msgDto);
                    }
                }
            }
        } else {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
        }
    }

    /**
     * 提现支付宝转账(个人)
     *
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Transactional
    public AlipayMchBatchTransVo alipayMch(UserTakeBalAlipayMchDto userTakeBalAlipayMchDto) {

        //提现id
        Long id = userTakeBalAlipayMchDto.getId();
        //支付宝授权id
        Long alipayMchAuthId = userTakeBalAlipayMchDto.getAlipayMchAuthId();
        //运营商id
        Long merId = userTakeBalAlipayMchDto.getMerId();
        if (id == null || alipayMchAuthId == null || merId == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        UserTakeBal userTakeBal = userTakeBalMapper.selectById(id, merId);

        if (userTakeBal == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该数据不存在或是3个月之前的历史数据");
        }

        if (userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_PENDING.getValue().intValue() && userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue().intValue()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该提现不是待处理状态或者自动提现失败");
        }

        Double takeBal = Tools.getDouble(userTakeBal.getTakeBal());
        if (takeBal.doubleValue() < 1.0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现金额必须大于等于1才能走支付宝个人转账");
        }

        //查询用户
        User user = userService.findUserInfo(userTakeBal.getUserId(), userTakeBal.getDeviceType(), merId);
        if (user == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //是否开启会员余额负数不提现验证
        if (Tools.getInteger(userTakeBalAlipayMchDto.getUserBalFlag()).intValue() == 1) { //开启，则需要判断会员余额是否为负数
            if (Tools.getDouble(user.getBalance()).doubleValue() < 0) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员余额为负数不处理");
            }
        }

        //该会员未填写支付宝账户
        if (StringUtils.isBlank(user.getAlipayAccount()) || StringUtils.isBlank(user.getAlipayName())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该会员没有支付宝账户信息");
        }

        //查询支付宝授权账户
        AlipayMchAuth alipayMchAuth = alipayMchAuthMapper.selectById(alipayMchAuthId, merId);
        if (alipayMchAuth == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该支付宝授权账号不存在");
        }

        //转账记录如果为空，则从授权账号里获取
        String transferinfo = userTakeBalAlipayMchDto.getTransferinfo();
        if (StringUtils.isBlank(transferinfo)) {
            transferinfo = alipayMchAuth.getTransferinfo();
        }
        //转账金额=提现金额+奖励金额
        Double amount = Math.add(Tools.getDouble(userTakeBal.getTakeBal()), Tools.getDouble(userTakeBal.getTakeRewardBal()));
        //支付宝个人转账
        String trandeNo = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();
        AlipayBatchPayDto alipayBatchPayDto = new AlipayBatchPayDto();
        alipayBatchPayDto.setBatchNo(trandeNo);
        alipayBatchPayDto.setPayTitle(transferinfo);
        alipayBatchPayDto.setPayDesc(transferinfo);
        alipayBatchPayDto.setTotalAmount(amount);
        List<AlipayBatchPayDto.PayDetail> payDetailList = new ArrayList<>();
        AlipayBatchPayDto.PayDetail payDetail = new AlipayBatchPayDto.PayDetail();
        payDetail.setAlipayAccount(user.getAlipayAccount());
        payDetail.setAlipayName(user.getAlipayName());
        payDetail.setAmount(amount);
        payDetail.setTradeNo(String.valueOf(id)); //将提现id作为tradeNo
        payDetailList.add(payDetail);
        alipayBatchPayDto.setPayDetails(payDetailList);
        AlipayMchBatchTransVo alipayMchBatchTransVo = alipayMchBatchPayService.batchPayCreate(alipayBatchPayDto, alipayMchAuth);
        if (alipayMchBatchTransVo != null && StringUtils.isNotBlank(alipayMchBatchTransVo.getPayUrl())) { //请求成功
            //添加批量转账
            int now = DateUtil.getNowTime();
            AlipayMchBatch alipayMchBatch = new AlipayMchBatch();
            alipayMchBatch.setId(IdWorker.getId());
            alipayMchBatch.setMerId(alipayMchAuth.getMerId());
            alipayMchBatch.setBatchTransId(alipayMchBatchTransVo.getBatchTransId());
            alipayMchBatch.setOutBatchNo(alipayBatchPayDto.getBatchNo());
            alipayMchBatch.setAuthUserId(alipayMchAuth.getUserId());
            alipayMchBatch.setAuthAppId(alipayMchAuth.getAuthAppId());
            alipayMchBatch.setAuthPartnerAppId(alipayMchAuth.getPartnerAppId());
            alipayMchBatch.setBatchStatus(AlipayMchBatchStatusEnum.WAIT_PAY.getKey());
            alipayMchBatch.setTotalItemCount(1); //总记录数为1
            alipayMchBatch.setTotalAmount(alipayBatchPayDto.getTotalAmount());
            alipayMchBatch.setAlipayurl(alipayMchBatchTransVo.getPayUrl());
            alipayMchBatch.setPayTitle(alipayBatchPayDto.getPayTitle());
            alipayMchBatch.setPayDesc(alipayBatchPayDto.getPayDesc());
            alipayMchBatch.setStatus(1); //等待付款
            alipayMchBatch.setType(1); //提现个人转账
            alipayMchBatch.setCreateTime(now);
            alipayMchBatch.setUpdateTime(now);
            alipayMchBatchMapper.insert(alipayMchBatch);
            //添加批量转账明细
            AlipayMchBatchDetail alipayMchBatchDetail = new AlipayMchBatchDetail();
            alipayMchBatchDetail.setId(IdWorker.getId());
            alipayMchBatchDetail.setMerId(alipayMchAuth.getMerId());
            alipayMchBatchDetail.setOutBatchNo(alipayBatchPayDto.getBatchNo());
            alipayMchBatchDetail.setOutBizNo(payDetail.getTradeNo());
            alipayMchBatchDetail.setTransAmount(payDetail.getAmount());
            alipayMchBatchDetail.setStatus(AlipayMchBatchDetailStatusEnum.APPLIED.getKey());
            alipayMchBatchDetail.setPayeeAccount(payDetail.getAlipayAccount());
            alipayMchBatchDetail.setPayeeName(payDetail.getAlipayName());
            alipayMchBatchDetail.setCreateTime(now);
            alipayMchBatchDetail.setUpdateTime(now);
            alipayMchBatchDetailMapper.insertSelective(alipayMchBatchDetail);
            //修改提现记录状态为处理中
            userTakeBal.setStatus(TakeBalStatusEnum.TBS_PROCESSING.getValue()); //处理中
            userTakeBal.setTransType(TransTypeEnum.ALIPAYPARTNER.getValue());
            userTakeBal.setUpdateTime(DateUtil.getNowTime());
            int i = userTakeBalMapper.updateStatus(userTakeBal);
            if (i != 1) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
            }
        }

        return alipayMchBatchTransVo;
    }

    /**
     * 批量支付宝转账(个人)
     *
     * @param userTakeBalAlipayMchBatchDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Transactional
    public AlipayMchBatchTransVo batchAlipayMch(UserTakeBalAlipayMchBatchDto userTakeBalAlipayMchBatchDto) {
        //提现id列表
        List<Long> idList = userTakeBalAlipayMchBatchDto.getIdList();
        //支付宝授权id
        Long alipayMchAuthId = userTakeBalAlipayMchBatchDto.getAlipayMchAuthId();
        //运营商id
        Long merId = userTakeBalAlipayMchBatchDto.getMerId();
        if (alipayMchAuthId == null || merId == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        if (idList == null && idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //查询支付宝授权账户
        AlipayMchAuth alipayMchAuth = alipayMchAuthMapper.selectById(alipayMchAuthId, merId);
        if (alipayMchAuth == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该支付宝授权账号不存在");
        }

        //转账记录如果为空，则从授权账号里获取
        String transferinfo = userTakeBalAlipayMchBatchDto.getTransferinfo();
        if (StringUtils.isBlank(transferinfo)) {
            transferinfo = alipayMchAuth.getTransferinfo();
        }

        List<AlipayBatchPayDto.PayDetail> payDetailList = new ArrayList<>();
        double totalAmount = 0.0;


        //临时保存可以正确提交的提现id列表
        List<Long> idList_correct = new ArrayList<>();

        for (Long id : idList) {
            UserTakeBal userTakeBal = userTakeBalMapper.selectById(id, merId);

            if (userTakeBal == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该数据不存在或是3个月之前的历史数据");
            }

            if (userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_PENDING.getValue().intValue() && userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue().intValue()) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该提现不是待处理状态或者自动提现失败");
            }

            Double takeBal = Tools.getDouble(userTakeBal.getTakeBal());

            if (takeBal.doubleValue() < 1.0) {
                userTakeBal.setStatus(TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue());
                userTakeBal.setTransType(TransTypeEnum.ALIPAYPARTNER.getValue());
                userTakeBal.setFailMsg("提现金额必须大于等于1才能走支付宝个人转账");
                userTakeBal.setUpdateTime(DateUtil.getNowTime());
                int i = userTakeBalMapper.updateStatus(userTakeBal);
                continue;
                //throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "提现金额必须大于等于1才能走支付宝个人转账");
            }

            //查询用户
            User user = userService.findUserInfo(userTakeBal.getUserId(), userTakeBal.getDeviceType(), merId);
            if (user == null) {
                userTakeBal.setStatus(TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue());
                userTakeBal.setTransType(TransTypeEnum.ALIPAYPARTNER.getValue());
                userTakeBal.setFailMsg("该用户不存在");
                userTakeBal.setUpdateTime(DateUtil.getNowTime());
                int i = userTakeBalMapper.updateStatus(userTakeBal);
                continue;
                //throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
            }

            //该会员未填写支付宝账户
            if (StringUtils.isBlank(user.getAlipayAccount()) || StringUtils.isBlank(user.getAlipayName())) {
                userTakeBal.setStatus(TakeBalStatusEnum.TBS_AUTO_TAKEBAL_FAIL.getValue());
                userTakeBal.setTransType(TransTypeEnum.ALIPAYPARTNER.getValue());
                userTakeBal.setFailMsg("该会员没有支付宝账户信息");
                userTakeBal.setUpdateTime(DateUtil.getNowTime());
                int i = userTakeBalMapper.updateStatus(userTakeBal);
                continue;
                //throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该会员没有支付宝账户信息");
            }

            //经过检验，可以办理支付宝个人转账的id添加到临时id列表
            idList_correct.add(id);

            //提现金额累计相加
            //转账金额=提现金额+奖励金额
            Double amount = Math.add(Tools.getDouble(userTakeBal.getTakeBal()), Tools.getDouble(userTakeBal.getTakeRewardBal()));
            totalAmount = Math.add(totalAmount, amount);

            AlipayBatchPayDto.PayDetail payDetail = new AlipayBatchPayDto.PayDetail();
            payDetail.setAlipayAccount(user.getAlipayAccount());
            payDetail.setAlipayName(user.getAlipayName());
            payDetail.setAmount(amount);
            payDetail.setTradeNo(String.valueOf(id)); //将提现id作为tradeNo
            payDetailList.add(payDetail);
        }


        //提现支付宝个人转账
        String trandeNo = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();
        AlipayBatchPayDto alipayBatchPayDto = new AlipayBatchPayDto();
        alipayBatchPayDto.setBatchNo(trandeNo);
        alipayBatchPayDto.setTotalAmount(totalAmount);
        alipayBatchPayDto.setPayTitle(transferinfo);
        alipayBatchPayDto.setPayDesc(transferinfo);
        alipayBatchPayDto.setPayDetails(payDetailList);

        //创建批量支付订单
        AlipayMchBatchTransVo alipayMchBatchTransVo = alipayMchBatchPayService.batchPayCreate(alipayBatchPayDto, alipayMchAuth);
        if (alipayMchBatchTransVo != null && StringUtils.isNotBlank(alipayMchBatchTransVo.getPayUrl())) { //请求成功
            //添加批量转账
            int now = DateUtil.getNowTime();
            AlipayMchBatch alipayMchBatch = new AlipayMchBatch();
            alipayMchBatch.setId(IdWorker.getId());
            alipayMchBatch.setMerId(alipayMchAuth.getMerId());
            alipayMchBatch.setBatchTransId(alipayMchBatchTransVo.getBatchTransId());
            alipayMchBatch.setOutBatchNo(alipayBatchPayDto.getBatchNo());
            alipayMchBatch.setAuthUserId(alipayMchAuth.getUserId());
            alipayMchBatch.setAuthAppId(alipayMchAuth.getAuthAppId());
            alipayMchBatch.setAuthPartnerAppId(alipayMchAuth.getPartnerAppId());
            alipayMchBatch.setBatchStatus(AlipayMchBatchStatusEnum.WAIT_PAY.getKey());
            alipayMchBatch.setTotalItemCount(payDetailList.size()); //总记录数为1
            alipayMchBatch.setTotalAmount(alipayBatchPayDto.getTotalAmount());
            alipayMchBatch.setAlipayurl(alipayMchBatchTransVo.getPayUrl());
            alipayMchBatch.setPayTitle(alipayBatchPayDto.getPayTitle());
            alipayMchBatch.setPayDesc(alipayBatchPayDto.getPayDesc());
            alipayMchBatch.setStatus(1); //等待付款
            alipayMchBatch.setType(1); //提现个人转账
            alipayMchBatch.setCreateTime(now);
            alipayMchBatch.setUpdateTime(now);
            alipayMchBatchMapper.insert(alipayMchBatch);
            //添加批量转账明细
            for (AlipayBatchPayDto.PayDetail payDetail : payDetailList) {
                AlipayMchBatchDetail alipayMchBatchDetail = new AlipayMchBatchDetail();
                alipayMchBatchDetail.setId(IdWorker.getId());
                alipayMchBatchDetail.setMerId(alipayMchAuth.getMerId());
                alipayMchBatchDetail.setOutBatchNo(alipayBatchPayDto.getBatchNo());
                alipayMchBatchDetail.setOutBizNo(payDetail.getTradeNo());
                alipayMchBatchDetail.setTransAmount(payDetail.getAmount());
                alipayMchBatchDetail.setStatus(AlipayMchBatchDetailStatusEnum.APPLIED.getKey());
                alipayMchBatchDetail.setPayeeAccount(payDetail.getAlipayAccount());
                alipayMchBatchDetail.setPayeeName(payDetail.getAlipayName());
                alipayMchBatchDetail.setCreateTime(now);
                alipayMchBatchDetail.setUpdateTime(now);
                alipayMchBatchDetailMapper.insertSelective(alipayMchBatchDetail);
            }

            for (Long id : idList_correct) {
                UserTakeBal userTakeBal = userTakeBalMapper.selectById(id, merId);
                if (userTakeBal != null) {
                    //修改提现记录状态为处理中
                    userTakeBal.setStatus(TakeBalStatusEnum.TBS_PROCESSING.getValue()); //处理中
                    userTakeBal.setTransType(TransTypeEnum.ALIPAYPARTNER.getValue());
                    userTakeBal.setUpdateTime(DateUtil.getNowTime());
                    int i = userTakeBalMapper.updateStatus(userTakeBal);
                    if (i != 1) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
                    }
                }
            }
        }
        return alipayMchBatchTransVo;
    }


    /**
     * 查询支付结果
     *
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public Boolean queryResult(UserTakeBalIdDto userTakeBalIdDto) {
        if (userTakeBalIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        UserTakeBal userTakeBal = userTakeBalMapper.selectById(userTakeBalIdDto.getId(), userTakeBalIdDto.getMerId());

        if (userTakeBal == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该数据不存在或是3个月之前的历史数据");
        }

        //查询用户
        User user = userService.findUserInfo(userTakeBal.getUserId(), userTakeBal.getDeviceType(), userTakeBalIdDto.getMerId());
        if (user == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        if (userTakeBal.getTransType().intValue() == TransTypeEnum.ALIPAYPARTNER.getValue().intValue()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付宝个人转账不能查询结果");
        }

        //查询支付结果
        UserTakeBalQueryResultDto userTakeBalTransAccountDto = new UserTakeBalQueryResultDto();
        userTakeBalTransAccountDto.setTakeBalId(userTakeBal.getId());
        userTakeBalTransAccountDto.setUserId(userTakeBal.getUserId());
        UzaiRespVo<Boolean> uzaiRespVo = userTakeBalFeignService.queryResult(userTakeBalTransAccountDto);
        return uzaiRespVo.getData();
    }

    /**
     * 查询待处理总金额
     *
     * @param userTakeBalQuery
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public UserTakeBalReportVo findUserTakeBalReport(UserTakeBalQuery userTakeBalQuery) {
        UserTakeBalReportVo userTakeBalReportVo = null;
        //查询历史数据统计
        //if (super.checkStartEndTimeIsHistoryQuery(userTakeBalQuery.getQueryStartTime(), userTakeBalQuery.getQueryEndTime(), null)) {
        if(StringUtils.isNotBlank(userTakeBalQuery.getTableSuffix())){
            //String tableSuffix = DateTime.of(userTakeBalQuery.getQueryEndTime() * 1000L).toString("yyMM");
            UzaiRespVo<UserTakeBalReportVo> uzaiRespVo = historyDataFeignService.searchTakeBalStatistics(userTakeBalQuery.getTableSuffix(), userTakeBalQuery);
            if (uzaiRespVo.getCode() != 200) {
                throw new BusinessException("提现列表统计失败");
            }
            userTakeBalReportVo = uzaiRespVo.getData();
        } else { // 查询90天内的订单数据
            userTakeBalReportVo = userTakeBalMapper.selectUserTakeBalReport(userTakeBalQuery);
        }
        return userTakeBalReportVo;
    }

    /**
     * 修改提现备注
     *
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void updateRemark(UserTakeBalUpdateRemarkDto userTakeBalUpdateRemarkDto) {
        if (userTakeBalUpdateRemarkDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        UserTakeBal userTakeBal = userTakeBalMapper.selectById(userTakeBalUpdateRemarkDto.getId(), userTakeBalUpdateRemarkDto.getMerId());

        if (userTakeBal == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该数据不存在或是3个月之前的历史数据");
        }
        Integer now = DateUtil.getNowTime();
        //修改提现备注
        userTakeBal.setRemark(userTakeBalUpdateRemarkDto.getRemark());
        userTakeBal.setUpdateTime(DateUtil.getNowTime());
        int i = userTakeBalMapper.updateById(userTakeBal);
        if (i != 1) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
        }
    }

    /**
     * 提现个人支付宝转账成功之后，修改提现明细信息
     *
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void updateAlipayMct(Long id, Integer status, Long merId) {
        int now = DateUtil.getNowTime();
        if (status == null || id == null || merId == null) {
            return;
        }

        UserTakeBal userTakeBal = userTakeBalMapper.selectById(id, merId);

        if (userTakeBal == null) {
            logger.error("----该数据不存在或是3个月之前的历史数据----");
            return;
        }

        if (userTakeBal.getStatus().intValue() != TakeBalStatusEnum.TBS_PROCESSING.getValue().intValue()) {
            logger.error("----该提现不是处理中----");
            return;
        }

        if (status.intValue() == 1) { //转账成功
            //修改提现记录状态为4-手动审核成功
            userTakeBal.setStatus(TakeBalStatusEnum.TBS_MANUAL_AUDIT_SUCCESS.getValue());
            userTakeBal.setTransType(TransTypeEnum.ALIPAYPARTNER.getValue());
            userTakeBal.setUpdateTime(now);
            userTakeBal.setPayTime(now);
            int i = userTakeBalMapper.updateStatus(userTakeBal);
            //如果失败，再次调用一次保存
            if (i != 1) {
                i = userTakeBalMapper.updateStatus(userTakeBal);
            }

            if (i == 1) {//修改成功，发送卡片消息
                //查询用户
                User user = userService.findUserInfo(userTakeBal.getUserId(), userTakeBal.getDeviceType(), merId);
                if (user == null) {
                    logger.error("--该会员不存在--");
                    return;
                }

                //查询机器人
                Device device = deviceService.findDeviceInfoByDeviceUniqueId(userTakeBal.getDeviceUniqueId(), userTakeBal.getDeviceType(), merId);
                if (device == null) {
                    //如果提现记录的机器人不存在，则取会员默认客户端机器人
                    device = deviceService.findDeviceInfoByDeviceUniqueId(user.getDeviceUniqueId(), user.getDeviceType(), user.getMerId());
                    if (device == null) {
                        logger.error("--该会员默认客户端不存在--");
                        return;
                    }
                }

                ConfigPlan configPlan = configPlanMapper.selectById(device.getConfigId(), merId);
                //接收消息业务会员id（机器人提现和群内提现）
                String bizUserId = null;
                //机器人提现
                if (StringUtils.isBlank(userTakeBal.getWxGroupId())) {
                    bizUserId = user.getBizUserId();
                    configPlan = configPlanMapper.selectById(device.getConfigId(), userTakeBal.getMerId());
                } else {//群内提现
                    bizUserId = userTakeBal.getWxGroupId();
                    if (DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(userTakeBal.getDeviceType())) {//个人微信群
                        //缓存中的微信群管理方案key
                        String redisKey_wxgroup_manageplan_key = String.format(RedisCacheKeyEnum.WXGROUP_MANAGEPLAN_CONFIG.getKey(), userTakeBal.getMerId(), device.getDeviceId(), userTakeBal.getWxGroupId());
                        Object wxgroup_manageplan_id = redisTemplate.opsForValue().get(redisKey_wxgroup_manageplan_key);
                        if (wxgroup_manageplan_id == null) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该群管理方案缓存");
                        }
                        configPlan = configPlanMapper.selectById((Long) wxgroup_manageplan_id, userTakeBal.getMerId());
                    } else {
                        //缓存中的企业微信群管理方案key
                        String redisKey_wxworkgroup_manageplan_key = String.format(RedisCacheKeyEnum.WXGROUP_WORK_MANAGEPLAN_CONFIG.getKey(), userTakeBal.getMerId(), device.getDeviceId(), userTakeBal.getWxGroupId());
                        Object wxworkgroup_manageplan_id = redisTemplate.opsForValue().get(redisKey_wxworkgroup_manageplan_key);
                        if (wxworkgroup_manageplan_id == null) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该群管理方案缓存");
                        }
                        configPlan = configPlanMapper.selectById((Long) wxworkgroup_manageplan_id, userTakeBal.getMerId());
                    }
                }

                if (configPlan == null) {
                    logger.error("--提现记录绑定的机器人的配置方案不存在--");
                    return;
                }

                //发送提现审核成功文本消息
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserTakeBalId(), merId);
                if (sysPlugin == null) {
                    logger.error("--提现记录绑定的机器人的配置方案中的提现插件不存在--");
                }

                //发送提现审核成功文本消息
                JSONObject jsonObject = JSONObject.parseObject(sysPlugin.getData());
                if (jsonObject != null) {
                    //支付宝自动提现成功（2023-03-21 增加,支付宝手动转账也是用这个回复语)
                    String message = jsonObject.getString("manual_alipay_take_succ");
                    if (StringUtils.isNotBlank(message)) {
                        //已提现总金额和冻结订单返利金额-从ES的会员额外信息index中获取
                        double takeBalTotalMoney = 0.00;
                        double frozenOrderRewardMoney = 0.00;

                        //查询用户额外信息
                        UserExtInfoQueryDto userExtInfoQueryDto = new UserExtInfoQueryDto();
                        userExtInfoQueryDto.setMerId(merId);
                        userExtInfoQueryDto.setDeviceType(DeviceTypeEnum.getByKey(userTakeBal.getDeviceType()).getId()); //个人用户
                        userExtInfoQueryDto.setBizUserId(user.getBizUserId());
                        userExtInfoQueryDto.setKeys(Arrays.asList("FrozenOrderRewardMoney", "TakeBalTotalMoney"));

                        StopWatch stopWatch = new StopWatch();
                        stopWatch.start();

                        UzaiRespVo<EsUserExtInfo> uzaiRespVo_userExtInfo = userExtInfoFeignService.getUserextinfo(userExtInfoQueryDto);
                        logger.info("----获取提现总金额----para={}, result={}", JSONObject.toJSONString(userExtInfoQueryDto), JSONObject.toJSONString(uzaiRespVo_userExtInfo));

                        stopWatch.stop();
                        logger.info("-获取提现总金额：" + stopWatch.prettyPrint());

                        //超过10秒的事务，报警
                        if (stopWatch.getTotalTimeSeconds() > 10) {
                            SysRunlogWarningDto sysRunlogWarningDto = new SysRunlogWarningDto();
                            sysRunlogWarningDto.setText("获取提现总金额，超过10秒的请求监控！\n类名：UserTakeBalServiceImpl" + "\n方法：updateAlipayMct" + "\n接口：getUserextinfo" + "\n耗时：" + stopWatch.getTotalTimeSeconds());
                            UzaiRespVo<Object> objectUzaiRespVo = uzaiManageFeignService.sysRunlogWarning(sysRunlogWarningDto);
                            logger.info("--调用官方钉钉报警超过10秒未处理完成的获取提现总金额接口---para={},result={}", JSONObject.toJSONString(sysRunlogWarningDto), JSONObject.toJSONString(objectUzaiRespVo));
                        }

                        if (uzaiRespVo_userExtInfo != null && uzaiRespVo_userExtInfo.getCode() == 200) {
                            EsUserExtInfo esUserExtInfo = uzaiRespVo_userExtInfo.getData();
                            if (esUserExtInfo != null) {
                                takeBalTotalMoney = esUserExtInfo.getTakeBalTotalMoney();
                                frozenOrderRewardMoney = esUserExtInfo.getFrozenOrderRewardMoney();
                            }
                        }

                        message = message.replace("[昵称]", user.getNickName());
                        message = message.replace("[提现金额]", String.valueOf(userTakeBal.getTakeBal()));
                        message = message.replace("[当前时间]", DateFormatUtil.formatDefault(new Date()));
                        message = message.replace("[已提现总金额]", String.valueOf(takeBalTotalMoney));
                        message = message.replace("[冻结订单返利金额]", String.valueOf(frozenOrderRewardMoney));
                        message = message.replace("[奖励金额]", String.valueOf(Tools.getDouble(userTakeBal.getTakeRewardBal())));
                        message = message.replace("[奖励积分]", String.valueOf(Tools.getInteger(userTakeBal.getTakeRewardInte())));
                        message = message.replace("[支付宝账号]", DesensitizeUtil.around(Tools.getStr(user.getAlipayAccount()), 3, 4));
                        message = message.replace("[支付宝姓名]", DesensitizeUtil.left(Tools.getStr(user.getAlipayName()), 1));

                        //发送MQ消息
                        MsgDto<NoticeMsgDto> msgDto = new MsgDto<>();
                        NoticeMsgDto noticeMsgDto = new NoticeMsgDto();
                        msgDto.setContent(noticeMsgDto);
                        msgDto.setId(IdWorker.getId());
                        msgDto.setDeviceType(device.getRecvmsgType());
                        msgDto.setDeviceUniqueId(userTakeBal.getDeviceUniqueId());
                        msgDto.setMerId(userTakeBal.getMerId());
                        msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
                        noticeMsgDto.setContent(message);
                        noticeMsgDto.setBizUserId(bizUserId);
                        noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
                        noticeMsgDto.setGroupId(null);
                        noticeMsgDto.setNickName(user.getNickName());
                        noticeMsgDto.setMsgSource(1);
                        noticeMsgDto.setDelay(0);
                        noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
                        noticeMsgPushProducerService.sendMessage(msgDto);
                    }
                }
            }
        } else {//转账失败
            //修改提现记录状态为0-待处理状态
            userTakeBal.setStatus(TakeBalStatusEnum.TBS_PENDING.getValue());
            userTakeBal.setTransType(0);
            userTakeBal.setUpdateTime(now);
            int i = userTakeBalMapper.updateStatus(userTakeBal);
            //如果失败，再次调用一次保存
            if (i != 1) {
                i = userTakeBalMapper.updateStatus(userTakeBal);
            }
        }
    }

}
